/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-03-07 15:55:15
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:00:32
 */


'use strict';
define([
    '../../../../../modules/common/service',
    '../../../../../modules/business/videoManage/base/baseView',
    '../../../../framework/bean/admanage',
    'text!../../tpl/monitor/table/editAd.html',
    '../../../../../modules/model/Global',
    '../../../../../modules/business/audienceManager/userAudienceKit',
], function(
    http,
    BaseView,
    admanageModel,
    tpl,
    Global,
    userAudienceKit
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        this.init = function(id, callback) {
            self.id = id;
            self.cpaSupport = null; //是否支持cpa
            self.callback = callback;
            self.render();
        }

        this.render = function() {
            if (!$('#editAdPanel')[0]) {
                $('body').append('<div id="editAdPanel"></div>');
            }
            self.$el = $('#editAdPanel');
            var params = {
                adSet_id: self.id
            }
            admanageModel.getAdSet(params, function(result) {
                var _editAdsetSidepanel = self.$el.sidepanel({
                    title: I18N.getText('management', 'editAdset'),
                    saveBtn: I18N.getText('management', 'saveAndClose'),
                    cancelBtn: I18N.getText('management', 'cancel'),
                    content: I18N.parse(tpl, window.pageName),
                    callback: self.updateCallback
                });

                var objective = result.adSet && result.adSet.campaign && result.adSet.campaign.objective ? result.adSet.campaign.objective : '';
                if ('' == objective || (objective != 'MOBILE_APP_INSTALLS' && objective != 'WEBSITE_CLICKS')){
                    $(_editAdsetSidepanel).find(".panel-body").html(I18N.getText('management', 'editAdDisable')).addClass("disable-edit");
                    $(_editAdsetSidepanel).find(".btn-primary").addClass("hide");
                    return;
                }

                $(_editAdsetSidepanel).find(".panel-footer").append('<div class="useraudience-area  hide">' +
                    '<button type="button" class="btn btn-generate">' + I18N.getText('management', 'generateAudience') +'</button>' +
                    '<div class="useraudience-success hide">' + I18N.getText('management', 'potentialReach') +'<span>20</span></div>'+
                    '</div>')
                self.objective = objective;
                self.adSet = result.adSet;
                self.condition =  result.condition;
                self.cpaSupport = result.cpa_support ? result.cpa_support : false;
                self.parseCondition();

                self.event();
                self.initRender(result);
            })
        }

        this.parseCondition = function(){
            //不投放地区
            self.buildExcludeKeys();
            //投放地区
            self.buildIncludeKeys();

            if (self.condition){
                var _condition = self.condition;
                if (_condition.age){
                    //年龄
                    $(".age-block").find(".item-r").append(_condition.age.ageMin + ' - ' + _condition.age.ageMax);
                }

                if (_condition.sex){
                    //性别
                    if (_condition.sex == 1){
                        $(".gender-block").find(".item-r").append(I18N.getText('createAd', 'all'));
                    } else if (_condition.sex == 2){
                        $(".gender-block").find(".item-r").append(I18N.getText('createAd', 'men'));
                    }else if (_condition.sex == 3){
                        $(".gender-block").find(".item-r").append(I18N.getText('createAd', 'women'));
                    }
                }

                if (_condition.platform && _condition.platform.length){
                    //平台相关信息
                    var _platform = _condition.platform[0];
                    if (_platform.userOS && _platform.userOS.length){
                        //版本
                        $(".os-block").find(".item-r").append(_platform.userOS[0] + I18N.getText('management', 'orAbove'));
                    }

                    if (_platform.userDevice && _platform.userDevice.length){
                        var showUD = '';
                        var isFirst = true;
                        $.each(_platform.userDevice, function(i, _de){
                            if (!isFirst){
                                showUD += ',';
                            }
                            showUD += _de;
                            isFirst = false;
                        });
                        $(".device-block").find(".item-r").append(showUD);
                    }
                }

            }


        }

        this.buildIncludeKeys =  function(){
            var self = this;
            self.locationIncludeKeys = [];
            if (self.condition && self.condition.regionAndPrices && self.condition.regionAndPrices.include
                && self.condition.regionAndPrices.include.length){
                var _includes = self.condition.regionAndPrices.include;
                $.each(_includes, function(i, _include){
                    if (_include.region && _include.region.length){
                        $.each(_include.region, function(i, _region){
                            self.locationIncludeKeys.push(_region.key);
                        })
                    }
                })
            }
        }

        this.buildExcludeKeys = function(){
            var self = this;
            self.locationExcludeKeys = [];
            if (self.condition && self.condition.regionAndPrices && self.condition.regionAndPrices.exclude
                && self.condition.regionAndPrices.exclude.length){
                var _excludes = self.condition.regionAndPrices.exclude;
                $.each(_excludes, function(i, _exclude){
                    if (_exclude.region && _exclude.region.length){
                        $.each(_exclude.region, function(i, _region){
                            self.locationExcludeKeys.push(_region.countryCode || _region.key);
                        })
                    }
                })
            }
        }

        this.event = function() {
            var self = this;
            //无线连接
            self.bindWirelessEvent();
            //选区
            self.bindLocationEvent();
            //版位
            self.bindPageTypeEvent();
            //性别
            self.bindGenderEvent();
            //关系
            self.bindConnectionsEvent();
            //预算出价
            self.bindBidEvent();
            //生成用户定位
            self.previewUserAudience();
        }

        this.bindWirelessEvent = function(){
            var self = this;
            $(".edit-ad-container").off("click",'input[name="wireless"]').on("click",'input[name="wireless"]', function(){
                self.showGenerate();
            })
        }

        /**
         * 增加详细定位事件
         */
        this.addDetailEvent = function(_option){
            var self = this;
            $(_option._element).unbind("mouseenter", "ul.muli-group").on("mouseenter", "ul.muli-group", function(){
                $(this).children("li").find(".alert-dismissible").addClass("hover");
                if (_option.canAdd()){
                    $(this).find("button.btn-plus").removeClass("hidden");
                }


                if (!_option.canAllDelete){
                    var len = $(this).children("li").length;
                    if (len > 1){
                        $(this).find("button.add-close").removeClass("hidden");
                    }
                } else {
                    $(this).find("button.add-close").removeClass("hidden");
                }

            });

            $(_option._element).unbind("mouseleave", "ul.muli-group").on("mouseleave", "ul.muli-group", function(){
                $(this).children("li").find(".alert-dismissible").removeClass("hover");
                $(this).find("button.add-close,button.btn-plus").addClass("hidden");
            });

            $(_option._element).unbind("click", "ul.muli-group button.btn-plus").on("click", "ul.muli-group button.btn-plus", function(){
                $(this).remove();
                if (_option.addCallBack){
                    _option.addCallBack($(this));
                }

            });

            $(_option._element).unbind("click", "ul.muli-group button.add-close").on("click", "ul.muli-group button.add-close", function(e){
                e.stopImmediatePropagation();
                var _li = $(this).parents("li");
                if (_option.canAdd()){
                    if(_li.has("button.btn-plus")){
                        var btnclone = _li.find("button.btn-plus").clone(true);
                        _li.prev().append(btnclone);
                    }
                }

                if (!_option.canAllDelete){
                    var len = _li.parent().children().length -1;
                    if(len <= 2){
                        _li.siblings().find("button.add-close").addClass("hidden");
                    }
                }

                if (_option.deleteCallBack){
                    _option.deleteCallBack(_li);
                }

                _li.remove();
            });
        }

        this.updateCallback = function($elem){
            if ( $(".panel-footer").find(".btn-primary").hasClass("disabled")){
                console.log("暂不能保存");
                return;
            }
            //对预算和出价的校验
            if ($(".budget").hasClass("error") || $(".budget").find("input").val() == ''){
                $(".budget").find("input").focus();
                return;
            }
            if ($(".bidamount").hasClass("error") || ($('input[name="autobid"]:checked').val() == '1' && $(".bidamount").find("input").val() == '')){
                $(".bidamount").find("input").focus();
                return;
            }

            var _updateValue = {}
            if (self.finalTarging){
                //用户定位
                _updateValue.targeting = self.finalTarging
            }

            //优化方向
            var cOptimizationGoal = $("div.ndp-drop-wrapper[name=optimization_goal]").data("val");
            if (self.adSet.optimization_goal != cOptimizationGoal){
                _updateValue.optimization_goal = cOptimizationGoal;
            }

            //支付方式
            var cBillingEvent = $("div.ndp-drop-wrapper[name=billing_event]").data("val");
            if (self.adSet.billing_event != cBillingEvent){
                _updateValue.billing_event = cBillingEvent;
            }

            //预算
            var oldBudget = self.adSet.lifetime_budget && self.adSet.lifetime_budget > 0
                ? {type : 'lifetime_budget', budget : self.adSet.lifetime_budget} : {type : 'daily_budget', budget : self.adSet.daily_budget};
            var newBudget = {type : $("div.ndp-drop-wrapper[name=budget_type]").data("val"), budget : Number(Number($(".budget").find("input").val()) * 100).toFixed(0)};

            if (newBudget.type != oldBudget.type ||  newBudget.budget != oldBudget.budget){
                if (newBudget.type == 'lifetime_budget'){
                    _updateValue.lifetime_budget = newBudget.budget;
                    _updateValue.daily_budget = 0;
                } else {
                    _updateValue.daily_budget = newBudget.budget;
                    _updateValue.lifetime_budget = 0;
                }
            }

            //自动出价与否
            var cIsAutobid = $('input[name="autobid"]:checked').val() == '0' ? true : false;
            _updateValue.is_autobid = self.adSet.is_autobid;
            if ((!self.adSet.is_autobid && cIsAutobid) || (self.adSet.is_autobid && !cIsAutobid)){
                _updateValue.is_autobid = cIsAutobid;
            }

            //单价
            var cbid_amount = isNaN(Number($(".bidamount").find("input").val())) ? 0 : Number(Number($(".bidamount").find("input").val()) * 100).toFixed(0);
            //每次都把出价带上,注释掉这一段
            // if ((!self.adSet.bid_amount && cbid_amount) || (self.adSet.bid_amount && !cbid_amount) || (cbid_amount != self.adSet.bid_amount)) {
                _updateValue.bid_amount = cbid_amount;
            // }

            //如果是自动出价,删除 _updateValue.bid_amount
            if(_updateValue.is_autobid&&_updateValue.bid_amount){
                delete _updateValue.bid_amount;
            }

            //投放类型 pacing_type
            var cPacing_type = $('input[name="pacing_type"]:checked').val();
            var oldPacing_type = self.adSet.pacing_type ? JSON.parse(self.adSet.pacing_type): [];
            if (oldPacing_type.indexOf(cPacing_type) == -1){
                if (cPacing_type == 'standard'){
                    var _i = oldPacing_type.indexOf('no_pacing');
                    if (_i > -1){
                        oldPacing_type.splice(_i,1);
                    }
                } else {
                    var _i = oldPacing_type.indexOf('standard');
                    if (_i > -1){
                        oldPacing_type.splice(_i,1);
                    }
                }

                oldPacing_type.push(cPacing_type);
                _updateValue.pacing_type = oldPacing_type;
            }

            if (Kit.isEmptyObject(_updateValue)){
                $elem.sidepanel('hide');
                console.log("未做任何修改")
                return;
            }

            var par = {
                "adSet_id": self.adSet.adset_id,    // 广告ID（必须项）
                "job_type":"update_ad_set",   //更新操作类型,
                "value": _updateValue
            };

            admanageModel.updateAdSet(par, function(result) {
                self.callback(result, 1, self.queryStatusOK, self.queryStatusFail); //调用 table.js queryStatus
            });
        }

        this.previewUserAudience = function(){
            var self = this;


            $(".btn-generate").off("click").on("click", function(){
                if ($(".btn-generate").hasClass("disabled")){
                    console.log("正在生成用户定位,请稍后");
                    return;
                }

                $(".item-content").removeClass("conflict-block");
                $(".item-r").addClass("hide");
                $(".useraudience-error ").addClass("hide");
                $(".useraudience-success").addClass("hide");
                $(".edit-tip").empty();

                console.log("生成用户定位");
                var conflictResult = {
                    isConflict : false,
                    items : []
                }

                //版位也至少要有一个
                //todo版位的交互
                var page_types = [];
                $.each($('input[name="page-type"]:checked'), function(i, page_type){
                    page_types.push($(page_type).val());
                })

                if (page_types.length == 0){
                    self.showDangerTip("warning", I18N.getText('management', 'selectPlacement'));
                    return;
                }

                //受众
                var _customAudiences = $(".custom-audience").select2("data");
                var custom_audiences = [];
                var excluded_custom_audiences = [];
                if (_customAudiences && _customAudiences.length > 0){
                    $.each(_customAudiences, function(i, _customAudience){
                        if (_customAudience.isClude && (_customAudience.isClude == "1" || _customAudience.isClude == 1)){
                            custom_audiences.push({id : _customAudience.id, name : _customAudience.name});
                        } else {
                            excluded_custom_audiences.push({id : _customAudience.id, name : _customAudience.name});
                        }
                    });
                }

                //地区
                //var _locations = $(".location-select2").select2("data");
                //
                //if  (_locations && _locations.length > 0){
                //    $.each(_locations, function(i, _location){
                //        if (_location.isClude && (_location.isClude == "1" || _location.isClude == 1)){
                //            if (!geo_locations){
                //                geo_locations = {};
                //            }
                //            //包括
                //            if (self.locationIncludeKeys.length  && self.locationIncludeKeys.indexOf(_location.id) == -1){
                //                //投了未指定的地区
                //                conflictResult.isConflict = true;
                //                if ( conflictResult.items.indexOf("location") == -1){
                //                    conflictResult.items.push("location");
                //                }
                //            }
                //
                //            if (self.locationExcludeKeys.length  && self.locationExcludeKeys.indexOf(_location.id) > -1){
                //                //投了已排除的地区
                //                conflictResult.isConflict = true;
                //                if ( conflictResult.items.indexOf("location") == -1){
                //                    conflictResult.items.push("location");
                //                }
                //            }
                //
                //            self.buildLocations(geo_locations, _location)
                //        } else {
                //            if (!excluded_geo_locations){
                //                excluded_geo_locations = {};
                //            }
                //            self.buildLocations(excluded_geo_locations, _location)
                //        }
                //    });
                //}

                var  locationResults = userAudienceKit.buildLocation({"locationArea" : $(".location-select2")})
                var geo_locations = locationResults.geo_locations;
                var excluded_geo_locations = locationResults.excluded_geo_locations;
                if (custom_audiences.length == 0 && !geo_locations){
                    self.showDangerTip("warning", I18N.getText('management', 'locationCustomAudience'));
                    return;
                }

                if (locationResults.isConflict && conflictResult.items.indexOf("location") == -1){
                    conflictResult.items.push("location");
                }

                if (!self.countLocation()){
                    //地区个数不能超过25个
                    return;
                }

                //地区类型
                if (geo_locations){
                    var _locationTypes = $("div.ndp-drop-wrapper[name=location_types]").data("val");
                    if (_locationTypes == 1){
                        //这个地区所有人
                        geo_locations.location_types = ["home","recent"];
                    } else if (_locationTypes == 2){
                        //在这里居住的用户
                        geo_locations.location_types = ["home"];
                    } else if (_locationTypes == 3){
                        //最近到过这里的用户
                        geo_locations.location_types = ["recent"];
                    } else {
                        //在这里旅游的用户
                        geo_locations.location_types = ["travel_in"];
                    }
                }

                //用户定位参数
                var targeting_spec = {};

                if (custom_audiences && custom_audiences.length > 0){
                    targeting_spec.custom_audiences = custom_audiences;
                }

                if (excluded_custom_audiences && excluded_custom_audiences.length > 0){
                    targeting_spec.excluded_custom_audiences = excluded_custom_audiences;
                }

                if (geo_locations){
                    targeting_spec.geo_locations = geo_locations;
                }

                if (excluded_geo_locations){
                    targeting_spec.excluded_geo_locations = excluded_geo_locations;
                }

                //只有应用安装 设置 user_os、wireless_carrier和user_device
                //user_os
                //"Android_ver_2.0_and_above"
                var user_os = $(".os-type").html() + '_ver_' + $("div.ndp-drop-wrapper[name=min-os]").data("val");
                if ($("div.ndp-drop-wrapper[name=max-os]").data("val") == -1){
                    user_os += "_and_above";
                } else {
                    user_os += "_to_" + $("div.ndp-drop-wrapper[name=max-os]").data("val");
                }
                targeting_spec.user_os  = [user_os];

                //设备
                var user_device = [];
                $.each($(".device").select2("data"), function(i, _device){
                    user_device.push(_device.name);
                });
                if (user_device.length > 0){
                    targeting_spec.user_device = user_device;
                }
                if (self.condition && self.condition.platform && self.condition.platform.length){
                    var _platform = self.condition.platform[0];
                    if (_platform.userOS && _platform.userOS.length){
                        if ((Number($("div.ndp-drop-wrapper[name=min-os]").data("val")) < Number(_platform.userOS[0]))){
                            conflictResult.isConflict = true;
                            conflictResult.items.push("os");
                        }
                    }

                    if (_platform.userDevice && _platform.userDevice.length && user_device.length){
                        var _cuds = _platform.userDevice;
                        $.each(user_device, function(i, _ud){
                            if (_cuds.indexOf(_ud) == -1){
                                conflictResult.isConflict = true;
                                if (conflictResult.items.indexOf("device") == -1){
                                    conflictResult.items.push("device");
                                }
                            }
                        })
                    }
                }


                //wireless
                if ($('input[name="wireless"]:checked').val() == 1){
                    targeting_spec.wireless_carrier = ["Wifi"];
                }

                //版位
                targeting_spec.page_types = page_types;

                //年龄
                targeting_spec.age_min = $("div.ndp-drop-wrapper[name=min-age]").data("val");
                targeting_spec.age_max = $("div.ndp-drop-wrapper[name=max-age]").data("val");
                if (self.condition && self.condition.age){
                    if (targeting_spec.age_min < self.condition.age.ageMin || targeting_spec.age_max > self.condition.age.ageMax){
                        conflictResult.isConflict = true;
                        conflictResult.items.push("age");
                    }
                }


                //性别
                var _gender = $('input[name="gender"]:checked').val()
                if ('0' != _gender){
                    targeting_spec.genders = [_gender];
                }

                if (self.condition && self.condition.sex){
                    var _csex = self.condition.sex;
                    if (_csex != 1){
                        //不是所有时
                        if ((_gender == '0' && _csex != 1) || (_gender == '1' && _csex != 2) || (_gender == '2' && _csex != 3)){
                            conflictResult.isConflict = true;
                            conflictResult.items.push("gender");
                        }
                    }
                }


                //语言
                var locales = [];
                $.each($(".locales").select2("data"), function(i, locale){
                    locales.push(locale.id)
                })
                if (locales.length > 0){
                    targeting_spec.locales = locales;
                }

                //关系
                var connections = [];
                $.each($(".connections").select2("data"), function(i, _connection){
                    connections.push({id : _connection.id, name : _connection.name});
                })
                if (connections.length > 0){
                    targeting_spec.connections = connections;
                }
                var friends_of_connections = [];
                $.each($(".friends_of_connections").select2("data"), function(i, _friends_of_connection){
                    friends_of_connections.push({id : _friends_of_connection.id, name : _friends_of_connection.name});
                })
                if (friends_of_connections.length > 0){
                    targeting_spec.friends_of_connections = friends_of_connections;
                }

                var excluded_connections = [];
                $.each($(".excluded_connections").select2("data"), function(i, _excluded_connection){
                    excluded_connections.push({id : _excluded_connection.id, name : _excluded_connection.name});
                })
                if (excluded_connections.length > 0){
                    targeting_spec.excluded_connections = excluded_connections;
                }

                // 详细定位
                var flexible_spec = [];
                $.each($(".detail-area").find(".detail"), function(i, _detail){
                   var _block =  self.buildDetail(_detail, {});
                    if (!Kit.isEmptyObject(_block)){
                        flexible_spec.push(_block);
                    }
                });
                if (flexible_spec.length > 0){
                    targeting_spec.flexible_spec = flexible_spec;
                }

                var exclusions = {};
                $.each($(".detail-exclude-area").find(".detail"), function(i, _detail){
                    exclusions =  self.buildDetail(_detail, {});
                });
                if (!Kit.isEmptyObject(exclusions)){
                    targeting_spec.exclusions = exclusions;
                }

                console.log(targeting_spec)
                if (conflictResult.isConflict){
                    self.showConflictConfirm(conflictResult.items,targeting_spec);
                    return;
                }

                self.generateUserAudience(targeting_spec);

            });
        }

        this.showConflictConfirm = function(_items, targeting_spec){
            var self = this;
            showConfirm(
                {containerClass :  'side-confirm',
                title : I18N.getText('management', 'confirmInfo'),
                content:I18N.getText('management', 'audienceConflict'),
                btnOK:I18N.getText('management', 'continueGenerate'), //确定
                btnCANCEL:I18N.getText('management', 'editAudience'),//取消
                onOK:function(){// 点击 “确认” 按钮回调函数
                    console.log("生成用户定位");
                    self.generateUserAudience(targeting_spec);
                },
                onCancel:function(){// 点击 “取消” 或者x 按钮回调函数
                    console.log("需要修改用户定位");
                    $.each(_items, function(i, _item){
                        $("." + _item + "-block").find(".item-content").addClass("conflict-block");
                        $("." + _item + "-block").find(".item-r").removeClass("hide");
                    })
                }
            });
        }

        this.generateUserAudience = function(targeting_spec){
            var self = this;
            $(".btn-generate").addClass("disabled");
            $(".panel-footer").find(".btn-primary").addClass("disabled");
            self.finalTarging = targeting_spec;
            var par = {targeting_spec : targeting_spec,
                account_id : self.adSet.account_id
            };
            http.work('/useraudiences/previewSimpleUserAudience', par, 'POST').then(function(res){
                if(res.flag == 'success') {
                    setTimeout(function(){
                        self.keepCalling(res.data.userAudienceCacheId);
                    },200)
                } else {
                    self.useraudienceError(res.msg);
                }
            },function(err){
                self.useraudienceError(I18N.getText('management', 'generateAudienceFailed'));
            })
        }

        this.keepCalling = function(_userAudienceCacheId){
            var par = {
                userAudienceCacheId : _userAudienceCacheId
            }
            http.work('/useraudiences/searchPreviewSimpleUserAudienceResult', par, 'POST').then(function(res){
                if(res.flag == 'success') {
                    var da = res.data;
                    if(da.isComplete){
                        //完成
                        $(".btn-generate").removeClass("disabled");
                        var people = da.previewUserAudienceResults && da.previewUserAudienceResults[0] && da.previewUserAudienceResults[0].people
                            ? da.previewUserAudienceResults[0].people : 0;
                        if (people > 0){
                            $(".useraudience-error ").addClass("hide");
                            $(".useraudience-success").removeClass("hide").find("span").html(Kit.toThousands(people));
                            $(".panel-footer").find(".btn-primary").removeClass("disabled");
                        } else {
                            console.log("生成用户定位失败");
                            var _msg = "【" + I18N.getText('management', 'generateAudienceFailed') + "】";
                            if (da.previewUserAudienceResults[0].exception){
                                console.log(da.previewUserAudienceResults[0].exception)
                                var _exception = JSON.parse(da.previewUserAudienceResults[0].exception);
                                if (_exception["error"] &&  _exception["error"]["error_data"] && _exception["error"]["error_data"]["showable_errors"]&& _exception["error"]["error_data"]["showable_errors"].length > 0){
                                    _msg += _exception["error"]["error_data"]["showable_errors"][0];
                                } else {
                                    _msg = da.previewUserAudienceResults[0].exception;
                                }
                            }
                            self.useraudienceError(_msg);
                        }
                    } else {
                        setTimeout(function(){self.keepCalling(_userAudienceCacheId) },200)   ;//返回数据不成功，再去请求，100毫秒后 直到成功为止
                    }
                }
            },function(err){
            })
        }

        this.buildDetail = function(_detail) {
            var flexible_spec_block = {}
            var _detailDatas = $(_detail).data("seldata");
            if (!_detailDatas){
                return flexible_spec_block;
            }
            $.each(_detailDatas, function (i, _detailData) {
                if (!flexible_spec_block[_detailData.type]) {
                    flexible_spec_block[_detailData.type] = [];
                }
                var subs = flexible_spec_block[_detailData.type];
                if (_detailData.type != 'college_years' && _detailData.tags && _detailData.tags.length > 0) {
                    var type = _detailData.type;
                    // "education_statuses":["2","11"] 教育程度
                    //性取向 "interested_in":["2"]
                    //感情状况 "relationship_statuses":["13"]
                    if (type == "education_statuses" || type == "interested_in" || type == "relationship_statuses") {
                        $.each(_detailData.tags, function (i, _tag) {
                            subs.push(_tag.id);
                        })
                    }

                    // 研究领域 "education_majors":[{"id":"103724069666039","name":"生物化学 （臨床化学）"}]
                    //学校 "education_schools":[{"id":"389830421097911","name":"恒生管理學院學生會 Hang Seng Management College Students' Union"}]
                    //族裔 "ethnic_affinity":[{"id":"6009609045383","name":"西班牙族裔人群（美国 - 主要语言为英语）"}]
                    //世代  "generation":[{"id":"6016645612183","name":"千禧一代"}]
                    // 住房条件 "household_composition":[{"id":"6024956935783","name":"Housemate-based Households"}]
                    //生活纪事 "life_events":[{"id":"6003053860372","name":"人在他乡"},{"id":"6021333340583","name":"Friends of Anniversary within 30 Days"}]
                    //父母 "family_statuses":[{"id":"6023005458383","name":"(01-02 Years) Parents with Toddlers "}]
                    //政治 "politics":[{"id":"6029977111383","name":"Likely To Engage in Politics (Conservative)"}]
                    //雇主 "work_employers":[{"id":"111897482177669","name":"生物学 （Ciencias biológicas）"}]
                    //行业 "industries":[{"id":"6008888961983","name":"IT 和技术"}]
                    //职位 "work_positions":[{"id":"112506898760777","name":"生意人"}]
                    //兴趣 "interests":[{"id":"6003277229371","name":"体育健身"}]
                    //行为 "behaviors":[{"id":"6023739659183","name":"Baseball 2015"},{"id":"6008297697383","name":"2 周前旅游回来"}]
                    //更多类别 "user_adclusters":[{"id":"6028974370383","name":"(A) Affinity for High Value Goods - India"},{"id":"6002714903772","name":"Family Movie"}]
                    if (type == "education_majors" || type == "education_schools" || type == "ethnic_affinity"
                        || type == "generation" || type == "household_composition" || type == "life_events"
                        || type == "family_statuses" || type == "politics" || type == "work_employers"
                        || type == "industries" || type == "work_positions" || type == "interests"
                        || type == "behaviors" || type == "user_adclusters"
                    ) {
                        $.each(_detailData.tags, function (i, _tag) {
                            subs.push({id: _tag.id, name: _tag.name});
                        })
                    }
                } else {
                    //大学就读年份 "college_years":["2016","2017","2018","2019","2020"]
                    console.log("大学就读年份");
                    _detailData.start = $(_detail).find("div[name='year-start']").data("val").val;
                    _detailData.end = $(_detail).find("div[name='year-end']").data("val").val;
                    for (var i = _detailData.start; i <= _detailData.end; i++) {
                        subs.push(i);
                    }
                }
            });
            return flexible_spec_block;
        }


        this.useraudienceError = function(_msg){
            var self = this;
            $(".useraudience-success ").addClass("hide");
            //$(".useraudience-error ").removeClass("hide");
            $(".btn-generate").removeClass("disabled");
            self.finalTarging = null;
            self.showDangerTip("danger", _msg);
        }

        this.showDangerTip = function(_type, _content){
            showTip({
                bind:$(".edit-tip"),
                holdon:null,
                type:_type,
                icon:"<i class='glyphicon glyphicon-alert'></i>",
                content:_content,
                through:true,
                close:true});
        }


        this.buildLocations = function(_locations, _location){
            if (_location.type == 'country'){
                if (!_locations["countries"]){
                    _locations["countries"] = [];
                }
                _locations["countries"].push(_location.country_code || _location.countryCode)
            } else if (_location.type == 'region'){
                if (!_locations["regions"]){
                    _locations["regions"] = [];
                }
                _locations["regions"].push({"key":_location.id,"name":_location.name,"country":_location.country_code || _location.countryCode});
            } else if (_location.type == 'city'){
                if (!_locations["cities"]){
                    _locations["cities"] = [];
                }
                var _city = {"distance_unit":_location.distance_unit || "kilometer",
                    "key":_location.id,"name":_location.name,"radius":_location.radius || 40,"country":_location.country_code || _location.countryCode};
                if (_location.region){
                    _city.region = _location.region;
                }
                _locations["cities"].push(_city);
            } else if (_location.type == 'zip'){
                if (!_locations["zips"]){
                    _locations["zips"] = [];
                }
                _locations["zips"].push ({"key":_location.id,"name":_location.name,"country":_location.country_code || _location.countryCode});
            } else if (_location.type == 'geo_market'){
                if (!_locations["geo_markets"]){
                    _locations["geo_markets"] = [];
                }
                _locations["geo_markets"].push ({"key" : _location.id,"name" : _location.name,"country" : _location.country_code || _location.countryCode});
            } else if (_location.type == 'electoral_district'){
                if (!_locations["electoral_districts"]){
                    _locations["electoral_districts"] = [];
                }
                _locations["electoral_districts"].push ({"key" : _location.id,"name" : _location.name,"country" : _location.country_code || _location.countryCode});
            } else if (_location.type == 'custom_location'){
                if (!_locations["custom_locations"]){
                    _locations["custom_locations"] = [];
                }
                _locations["custom_locations"].push ({
                    "distance_unit" : _location.distance_unit,
                    "latitude" : _location.latitude,
                    "longitude" : _location.longitude,
                    "radius" : _location.radius,
                    "country" : _location.country ||  _location.country_code || _location.countryCode
                });
            } else {
                console.log("其他地区类型");
            }
        }


        this.showGenerate = function(){
            $(".useraudience-area").removeClass("hide");
            $(".panel-footer").find(".btn-primary").addClass("disabled");
        }
        this.bindBidEvent = function(){
            var self = this;
            //自动出价与否相关事件
            $('input[name="autobid"]').off("change").on("change", function(){
                if ($(this).val() == 0){
                    //自动
                    $(".bidamount").addClass("hide").removeClass("error").removeClass("warning");
                    $(".bidamount-reminder").html("");
                    $(".bidamount").find("input").val('');
                    $(".budget").find("input").trigger("keyup");

                    //自动出价只能是标准
                    $('input[name="pacing_type"][value="standard"]').prop("checked", true);
                    $('input[name="pacing_type"][value="no_pacing"]').attr("disabled","disabled");
                } else {
                    $(".bidamount").removeClass("hide");
                    $('input[name="pacing_type"][value="no_pacing"]').removeAttr("disabled");
                }
            });

            //预算
            $(".edit-ad-container").off('keyup', '.budget>input').on('keyup', '.budget>input', function(e){
                if ($(this).val() == ''){
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error")
                    return;
                }

                var info = {
                    billing_event: $("div.ndp-drop-wrapper[name=billing_event]").data("val")
                }

                var warning = Kit.validateBudget(info, $(".bidamount").find("input").val(),
                    $(this).val(),
                    $(".budget_type").data("val"),
                    self.adSet.start_utc_time, self.adSet.end_utc_time);

                if (warning){
                    $(".budget-reminder").html(warning).removeClass("hide");
                    $(this).parent().addClass("error")
                } else {
                    $(".budget-reminder").html("").addClass("hide");
                    $(this).parent().removeClass("error");
                }
            });

            //单价
            $(".edit-ad-container").off('keyup', '.bidamount>input').on('keyup', '.bidamount>input', function(e){
                //修改单价，预算需要重新校验
                $(".budget").find("input").trigger("keyup");

                var _validateReault = Kit.validateBidAmount($(this).val(), $(this).attr("min"), $(this).attr("max"));
                console.log(_validateReault);
                if (!_validateReault){
                    $(".bidamount-reminder").html("");
                    $(this).parent().removeClass("error").removeClass("warning");
                } else {
                    $(".bidamount-reminder").html(_validateReault.msg);
                    if (_validateReault.type == "error"){
                        $(this).parent().addClass("error").removeClass("warning");
                        $(".bidamount-reminder").addClass("bid-error").removeClass("bid-warning");
                    } else {
                        $(this).parent().addClass("warning").removeClass("error");
                        $(".bidamount-reminder").addClass("bid-warning").removeClass("bid-error");
                    }
                }
            });
        }

        this.bindConnectionsEvent = function(){
            $('input[name="connection"]').off("change").on("change", function(e, _isFirst){
                if ($(this).prop("checked")){
                    $(".connection-area").removeClass("hide");
                } else {
                    $(".connection-area").addClass("hide");
                }

                //当有具体的关系选项时，添加关系与否的变更才会影响到用户定位
                var _connections = $(".connections").select2("data");
                var _friendsOfConnections = $(".friends_of_connections").select2("data");
                var _excludedConnections = $(".excluded_connections").select2("data");
                if (!_isFirst && (_connections.length > 0 || _friendsOfConnections.length > 0|| _excludedConnections.length > 0)) {

                    self.showGenerate();
                }

            })
        }

        this.bindPageTypeEvent = function(){
            var self = this;
            $(".edit-ad-container").off("click",'input[name="page-type"]').on("click",'input[name="page-type"]', function(){
               self.showGenerate();

                //移动应用受众网络版位依赖于移动版动态消息版位
                if ($(this).val() == 'mobilefeed' && !$(this).prop('checked')){
                    $('input[name="page-type"][value="mobileexternal"]').attr("checked",false);
                    $('input[name="page-type"][value="mobileexternal"]').prop("checked",false);
                }

                if ($(this).val() == 'mobileexternal' && $(this).prop('checked')){
                    $('input[name="page-type"][value="mobilefeed"]').attr("checked",true);
                    $('input[name="page-type"][value="mobilefeed"]').prop("checked",true);
                }
            })
        }
        this.bindGenderEvent = function(){
            $(".edit-ad-container").off("change",'input[name="gender"]').on("change",'input[name="gender"]', function(e, _isShowNot){
                if (!_isShowNot){
                    self.showGenerate();
                }
            })
        }
        this.bindLocationEvent  = function(){
            var self = this;
            $(".c-location").off("click").on("click", function(e){
                $(".loc-magic-drop").find("input[type=checkbox]:checked").prop("checked",false);
                $(".loc-magic-drop").removeClass("hide");
            })

            $(".magic-ok").off("click").on("click", function(e){
                e.stopImmediatePropagation();
                var _regionType = $(".magic-content").attr("type");
                var _selects = [];
                if (_regionType == 'include'){
                    //指定地区
                    var _checked = $(".magic-content").find("ul>li:has(input:checked)");

                    $.each(_checked, function(i, _item){
                        var o = {
                            "id":$(_item).data("value"),
                            "key":$(_item).data("value"),
                            "countryCode": $(_item).attr("country-code"),
                            "type": $(_item).data("title"),
                            "text": $(_item).text().trim(),
                            "name":$(_item).attr("c-name"),
                            "isClude": $("div.ndp-drop-wrapper[name=location-clude]").data("val")
                        }
                        _selects.push(o)
                    });

                } else {
                    //全球
                    var _checked = $(".magic-content").find("input:checked");
                    $.each(_checked, function(i, _item){
                        var _locations = Global[$(_item).attr("key")];
                        var _locationBlock = Kit.region(_locations, $(_item).val());
                        var type = $(_item).data('title');
                        $.each(_locationBlock, function(j, _location){
                            if (self.locationExcludeKeys.indexOf(_location.countryCode) == -1){
                                var o = {
                                    "id":_location.countryCode,
                                    "key":_location.countryCode,
                                    "countryCode":_location.countryCode,
                                    "text":_location.name+'('+_location.countryCode+')',
                                    "name":_location.name,
                                    "type": type,
                                    "isClude" :  $("div.ndp-drop-wrapper[name=location-clude]").data("val")
                                }
                                _selects.push(o);
                            }
                        });
                    });
                }

                if (_selects.length > 0){
                    $(".location-select2").empty();
                    $(".location-select2").select2('data',_selects);
                    self.countLocation();
                    self.showGenerate();
                }

                //选区确定
                $(".loc-magic-drop").addClass("hide");
            })

            $("body").off('click').bind('click', function(e){
                if ($(e.target).hasClass("c-location") || $(e.target).parents(".c-location") > 0){
                    $(".loc-magic-drop").removeClass("hide");
                    return;
                }
                if ($(e.target).parents('.loc-magic-drop').length == 0 && !$(".loc-magic-drop").hasClass("hide")){
                    $(".loc-magic-drop").addClass("hide");
                }
            });

        }
        this.initRender = function(_result) {
            var self = this;
            self.renderOs(_result.condition, _result.targeting_spec);
            self.renderDevice(_result.condition, _result.targeting_spec);
            self.renderWireless(_result.condition, _result.targeting_spec);
            self.renderPageType(_result);
            self.renderCustomAudience(_result.targeting_spec);
            self.renderLocation(_result.condition, _result.targeting_spec);
            self.renderAge(_result.targeting_spec);
            userAudienceKit.initAge({
                age_min : _result.targeting_spec.age_min,
                age_max : _result.targeting_spec.age_max,
                container : $(".edit-ad-container"),
                changeCallBack : function(){
                    self.showGenerate();
                }
            })
            self.renderGender(_result.condition, _result.targeting_spec);
            self.renderLocales(_result.targeting_spec);
            //详细定位
            self.renderDetail(_result.targeting_spec);
            //渲染关系
            self.renderConnection(_result.adSet.account_id, _result.targeting_spec);
            ////渲染其他
            //self.renderOther();
            //渲染出价
            self.renderBid(_result.adSet, _result.condition);
        }

        self.renderDetail = function(_originTargetingSpec){
            var self = this;
            //初始化
            $(".ndp-blend-wrapper").blend({
                //containerClass:'detail-area-c',
                recdata:[],//推荐下拉菜单数据，点击手型
            })


            http.work('/search/targetingbrowse', {locale : I18N.language}, 'POST').then(function(res){
                if(res.flag == 'success') {
                    self.targetingbrowses = res.data || [];
                    self.leafNodes = {};
                    parseTargetingbrowses(self.targetingbrowses,  self.leafNodes);
                }
            }).done(function() {
                console.log("回填");

                //排除用户事件
                self.excludeDetailEvent();

                self.suggessionEvent();

                //增加详细定位事件
                self.addDetailEvent({
                    _element : $(".detail-area"),
                    canAdd : function(){
                        return true;
                    },
                    addCallBack : function(_contex){
                        console.log("增加详细定位组");
                        self.initBlend([],[]);
                    },
                    deleteCallBack : function(_contex){
                        console.log("删除回调");
                        var _cSeldatas = $(_contex).find(".detail").data("seldata");
                        if (_cSeldatas && _cSeldatas.length > 0){
                            self.showGenerate();
                        }
                    }
                    //,canAllDelete : true
                });

                self.collegeyearEvent();

                var _blocks = self.getSeldatas(_originTargetingSpec);
                $.each(_blocks, function(i, _block){
                    self.initBlend(_block.seldata, _block.selects);
                })

                //flexible_spec 包含至少符合一项条件的用户
                if (_originTargetingSpec.flexible_spec && _originTargetingSpec.flexible_spec.length > 0){
                    $.each(_originTargetingSpec.flexible_spec, function(i, _flexible_spec){
                        var _blocks = self.getSeldatas(_flexible_spec);
                        var _seldatas = [];
                        var _selects = []
                        $.each(_blocks, function(i, _block){
                            _seldatas = _seldatas.concat(_block.seldata);
                            _selects = _selects.concat(_block.selects);
                            _block.seldata = null;
                            _block.selects = null;
                            _block = null;
                        })
                        self.initBlend(_seldatas, _selects);
                    })
                }

                // 排除用户
                if (_originTargetingSpec.exclusions && !Kit.isEmptyObject(_originTargetingSpec.exclusions)){
                    console.log("排除用户");
                    var _blocks = self.getSeldatas(_originTargetingSpec.exclusions);
                    var _seldatas = [];
                    var _selects = []
                    $.each(_blocks, function(i, _block){
                        _seldatas = _seldatas.concat(_block.seldata);
                        _selects = _selects.concat(_block.selects);
                        _block.seldata = null;
                        _block.selects = null;
                        _block = null;
                    })
                    $(".exclude-detail-link").trigger("click", [_seldatas, _selects]);
                }

                if (!self.newDetail){
                    self.initBlend([], []);
                }
            });

            function parseTargetingbrowses(_targetingbrowses, leafNodes){
                $.each(_targetingbrowses, function(i, _targetingbrowse){
                    if (_targetingbrowse.sub && _targetingbrowse.sub.length == 0){
                        _targetingbrowse.sub = null;
                        //研究领域、学校、雇主、职位 支持搜索
                        if ('education_majors' == _targetingbrowse.type
                            || 'education_schools' == _targetingbrowse.type
                        || 'work_employers' == _targetingbrowse.type
                        || 'work_positions' == _targetingbrowse.type){
                            _targetingbrowse.search = true;
                        }

                        if ('college_years' == _targetingbrowse.type){
                            _targetingbrowse.start = 2016;
                            _targetingbrowse.end = 2020;
                        }
                        _targetingbrowse.locale = (!I18N.language ||  I18N.language == 'zh-cn') ? 'zh_CN' : 'en_US';
                        _targetingbrowse.audience_size = _targetingbrowse.audience_size ? Kit.toThousands(_targetingbrowse.audience_size) :null;

                        if (_targetingbrowse.type && _targetingbrowse.id){
                            //有type和id认为是叶子节点，且是每个叶子的唯一标示
                            leafNodes[_targetingbrowse.type +  "_" +_targetingbrowse.id] = _targetingbrowse;
                        }
                    } else {
                        parseTargetingbrowses(_targetingbrowse.sub, leafNodes);
                    }
                });
            }
        }

        this.collegeyearEvent = function(){
            $(".edit-ad-container").off("ITEM_CHANGE", "div[name='year-start']").on("ITEM_CHANGE", "div[name='year-start']", function(e){
                var c_mi = e.originalEvent.data.val;
                var _maxDrop = $(this).siblings("div[name='year-end']");
                var c_mx  =  _maxDrop.data("val").val;
                if (c_mx < c_mi){
                    _maxDrop.drop3("val", {name :  c_mi , val : c_mi});
                }
            });

            $(".edit-ad-container").off("ITEM_CHANGE", "div[name='year-end']").on("ITEM_CHANGE", "div[name='year-end']", function(e){
                var c_mx = e.originalEvent.data.val;
                var _minDrop = $(this).siblings("div[name='year-start']");
                var c_mi  =  _minDrop.data("val").val;
                if (c_mx < c_mi){
                    _minDrop.drop3("val", {name :  c_mx , val : c_mx});
                }
            });
        }

        this.excludeDetailEvent  = function(){
            var self = this;
            //渲染排除
            self.addDetailEvent({
                _element : $(".detail-exclude-area"),
                canAdd : function(){
                    return false;
                },
                deleteCallBack : function(_contex){
                    console.log("删除回调");
                    $(".exclude-detail-link").parent().removeClass("hide");
                    var _cSeldatas = $(_contex).find(".detail").data("seldata");
                    if (_cSeldatas && _cSeldatas.length > 0){
                        self.showGenerate();
                    }
                }
                ,canAllDelete : true
            });

            $(".exclude-detail-link").off("click").on("click", function(e, _initDatas, _initSelects){
                console.log("排除用户事件")
                e.preventDefault();
                e.stopImmediatePropagation();
                $(this).parent().addClass("hide");
                var selDatas = _initDatas || [];
                var selects = _initSelects || [];
                $(".detail-exclude-area").removeClass("hide");
                self.initBlend(selDatas, selects, $(".detail-exclude-area").find(".muli-group"), I18N.getText('management', 'excludeDetailedTargeting'));

            })
        }

        this.initBlend = function(_seldata, _selects, _perantD, _detailTitle){
            var s_deatil
            if (self.newDetail || _perantD){
                s_deatil =  $('<li class="s-detail-area add">' +
                    '<div class="alert alert-dismissible">' +
                    '<button type="button" class="close add-close hidden" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>' +
                    '<span class="detail-title">' + (_detailTitle ? _detailTitle : I18N.getText('management', 'includeDetailedTargeting')) + '</span>' +
                    '<div class="ndp-blend-wrapper detail"></div>' +
                    '</div>' +
                    '</div>' +
                    '<button class="btn btn-default btn-plus hidden"><i class="glyphicon glyphicon-plus"></i></button>' +
                    '</li>');
                if (_perantD){
                    $(_perantD).append(s_deatil);
                    console.log(s_deatil.find(".detail").width())
                    console.log(s_deatil.find(".detail").width())
                } else {
                    self.newDetail = true;
                    //删除其他的添加按钮
                    $(".detail-area>").find(".btn-plus").remove();
                    $(".detail-area").find(".muli-group").append(s_deatil);
                }

            } else {
                self.newDetail = true;
                s_deatil = $(".detail-area>").find(".s-detail-area");
            }

            s_deatil.data("selects", _selects || []);
            var the = s_deatil.find(".detail").empty().blend({
                containerClass : 'detail-area-c',
                icon : '<span class="recommendation word-button">' + I18N.getText('management', 'recommendation') + '</span>',
                recdata:self.targetingbrowses,//推荐下拉菜单数据，点击手型
                seldata:_seldata,
                ajaxOptions: {
                    type: "POST",
                    url:  cors_config.api_host + '/search/searchInterests',
                    dataType: 'json',
                    data: function (_s) {
                        return{
                            param:JSON.stringify({
                                q: _s,
                                locale: I18N.language,
                                "type":"adinterest"
                            })
                        }
                    },
                    xhrFields: { withCredentials: true},
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            data: []
                        };
                        if (res.flag == 'success'){
                            $(res.data).each(function(i, _interest) {
                                _interest.audience_size = _interest.audienceSize ? Kit.toThousands(_interest.audienceSize) : null;
                                _interest.audienceSize = _interest.audienceSize ? Kit.toThousands(_interest.audienceSize) : null;
                                _interest.type = 'interests';
                                _interest.path = [I18N.getText('management', 'interests'), I18N.getText('management', 'additionalInterests')];
                                _interest.parent = I18N.getText('management', 'interests') + " > " + I18N.getText('management', 'additionalInterests');

                            })
                            opts.data = res.data;
                        }

                        return opts;
                    }
                },
                formatNoMatches : I18N.getText('management', 'noResultsFound'),
                returnList : I18N.getText('management', 'returnList'),
                pastecallback:function(key,dropup,dat,Tool){
                    var _key = $.trim(key);
                    if (_key == ''){
                        return;
                    }
                    //粘贴兴趣词
                    var _locale = !I18N.language || I18N.language == 'zh-cn' ? 'zh_CN' : 'en_US';
                    var param = {interestList : _key, locale : _locale};
                    var loadingArea = s_deatil.find(".detail-area-c");
                    Kit.loading.show(loadingArea);
                    http.work("/search/searchInterestList",param, "POST").then(function(result){
                        s_deatil.find(".detail").blend("close");
                        if(typeof(result)=="string") result = JSON.parse(result);
                        var da = result.data;
                        if(!da || 0 == da.length ){
                            return false;
                        }
                        var _selects = s_deatil.data("selects");
                        var _key;
                        var newDatas = [];
                        var pV;
                        $.each(da,function(i,v){
                            if (v.valid){
                                _key = "interests" + "_" + v.id;
                                if (_selects.indexOf(_key) == -1){
                                    //未选择过
                                    _selects.push(_key);
                                    pV =  self.leafNodes[_key];
                                    if (!pV){
                                        pV = v;
                                        pV.path = I18N.getText('management', 'interests') + "#" + I18N.getText('management', 'additionalInterests');
                                    } else {
                                        pV = {
                                            path : pV.path.join("#"),
                                            id : pV.id,
                                            name : pV.name
                                        }
                                    }
                                    pV.type = "interests";
                                    pV.path = pV.path.replace(/\s/g,"");
                                    pV.locale = _locale;
                                    newDatas.push(pV)
                                }
                            }
                        });
                        if (newDatas.length > 0){
                            s_deatil.find(".detail").blend("selectDAT", newDatas);
                            s_deatil.data("selects", _selects);
                        }
                    },function(err){}).done(function(){
                        s_deatil.find(".detail").blend("close");
                        Kit.loading.hide(loadingArea);
                    });

                }
            }).on("ITEM_CLICK",function(e){
                var _d = e.originalEvent.data;
                //研究领域、学校、雇主、职位 支持搜索
                if (_d.search){
                    var sR = self.searchAjax(_d);
                    the.updateOption(sR.reajaxOptions);// 更新 reajaxOption 配置 用于搜索
                    the.updateTip(sR.tip)
                } else {
                    console.log('不是搜索')
                    //只有兴趣的时候会进行联想
                    if (_d.type == "interests"){
                        console.log('兴趣联想')
                        self.interestsSuggession(s_deatil.find(".suggestion-area"), _d.name, !I18N.language ||  I18N.language == 'zh-cn'? "zh_CN" : 'en_US');
                    }
                    var _selects = s_deatil.data("selects");
                    var _key = "" + _d.type + "_" + _d.id;
                    if (_selects.indexOf(_key) == -1){
                        _selects.push("" + _d.type + "_" + _d.id);
                        s_deatil.data("selects", _selects);
                    }
                    //点击则用户定位改变，可生成用户定位
                    self.showGenerate();
                }
            }).on("TAG_RESIGN",function(e){
                console.log("删除tag");
                var _ds = e.originalEvent.data;
                // 点击tag前面的x 删除一个tag
                var _selects = s_deatil.data("selects");
                $.each(_ds, function(i, _d){
                    var _index = _selects.indexOf("" + _d.type + "_" + _d.id);
                    if (_index > -1){
                        _selects.splice(_index, 1);
                    }
                })
                s_deatil.data("selects", _selects);

                self.showGenerate();
            }).on("SERIAL_RESIGN",function(e){
                console.log("删除一行");
                var _ds = e.originalEvent.data;
                var _selects = s_deatil.data("selects");
                $.each(_ds, function(i, _b){
                    $.each(_b.tags, function(i, _d){
                        var _index = _selects.indexOf("" + _d.type + "_" + _d.id);
                        if (_index > -1){
                            _selects.splice(_index, 1);
                        }
                    })
                })
                s_deatil.data("selects", _selects);

                //删除一行
                self.showGenerate();
            }).on("BLEND_DROPUP_SCROLL", function(){
                $.each(s_deatil.find(".ndp-drop3-wrapper"), function(i, _drop3){
                    console.log("关闭drop3")
                    $(_drop3).drop3("close");
                });
            }).on("close", function(e){
                console.log("关闭恢复初始状态");
                s_deatil.find(".suggestion-area").addClass("hide");
            });
            var sA = $('<div class="suggestion-area hide"><ul></ul></div>');
            s_deatil.find(".detail-area-c").append(sA);
            sA.width(s_deatil.find(".blend-dropup").width());
        }

        this.searchAjax = function(_d){
            var result = {
                reajaxOptions : null,
                tip : ''
            }
            if (_d.type == 'education_majors'){
                //研究领域
                result.reajaxOptions = {
                    type: "POST",
                    url:  cors_config.api_host + '/search/searchAdeducationmajor',
                    dataType: 'json',
                    data: function (_s) {
                        return{
                            param:JSON.stringify({
                                q: _s,
                                locale: I18N.language,
                                "type":"adeducationmajor"
                            })
                        }
                    },
                    xhrFields: { withCredentials: true},
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            data: []
                        };
                        if (res.flag == 'success'){
                            $(res.data).each(function(i, _adeducationmajor) {
                                _adeducationmajor.audience_size = _adeducationmajor.coverage ? Kit.toThousands(_adeducationmajor.coverage) : null;
                                _adeducationmajor.type = 'education_majors';
                                _adeducationmajor.path = [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'),I18N.getText('management', 'fieldsOfStudy')];
                                _adeducationmajor.parent = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'fieldsOfStudy');
                                //path: ["个人情况", "学历", "研究领域", "生物化学 （臨床化学）"]
                            })
                            opts.data = res.data;
                        }

                        return opts;
                    }
                }
                result.tip = I18N.getText('management', 'educationMajorsTip')
            } else if (_d.type == 'education_schools'){
                //学校
                result.reajaxOptions = {
                    type: "POST",
                    url:  cors_config.api_host + '/search/searchAdeducationschool',
                    dataType: 'json',
                    data: function (_s) {
                        return{
                            param:JSON.stringify({
                                q: _s,
                                locale: I18N.language,
                                "type":"adeducationschool"
                            })
                        }
                    },
                    xhrFields: { withCredentials: true},
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            data: []
                        };
                        if (res.flag == 'success'){
                            $(res.data).each(function(i, _adeducationschool) {
                                _adeducationschool.audience_size = _adeducationschool.coverage ? Kit.toThousands(_adeducationschool.coverage) : null;
                                _adeducationschool.type = 'education_schools';
                                _adeducationschool.path = [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'schools')];
                                _adeducationschool.parent = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'schools');
                                //path: ["个人情况", "学历", "研究领域", "生物化学 （臨床化学）"]
                            })
                            opts.data = res.data;
                        }

                        return opts;
                    }
                }
                result.tip = I18N.getText('management', 'schoolTip')
            } else if (_d.type == 'work_employers'){
                //雇主E
                result.reajaxOptions = {
                    type: "POST",
                    url:  cors_config.api_host + '/search/searchAdworkemployer',
                    dataType: 'json',
                    data: function (_s) {
                        return{
                            param:JSON.stringify({
                                q: _s,
                                locale: I18N.language,
                                "type":"adworkemployer"
                            })
                        }
                    },
                    xhrFields: { withCredentials: true},
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            data: []
                        };
                        if (res.flag == 'success'){
                            $(res.data).each(function(i, _adworkemployer) {
                                _adworkemployer.audience_size = _adworkemployer.coverage ? Kit.toThousands(_adworkemployer.coverage) : null;
                                _adworkemployer.type = 'work_employers';
                                _adworkemployer.path = [I18N.getText('management', 'demographics'), I18N.getText('management', 'work'), I18N.getText('management', 'employers')];
                                _adworkemployer.parent = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'work') + " > " + I18N.getText('management', 'employers');
                                //path: ["个人情况", "学历", "研究领域", "生物化学 （臨床化学）"]
                            })
                            opts.data = res.data;
                        }

                        return opts;
                    }
                }
                result.tip = I18N.getText('management', 'workmployersTip')
            } else if (_d.type == 'work_positions'){
                //职位
                result.reajaxOptions = {
                    type: "POST",
                    url:  cors_config.api_host + '/search/searchAdworkposition',
                    dataType: 'json',
                    data: function (_s) {
                        return{
                            param:JSON.stringify({
                                q: _s,
                                locale: I18N.language,
                                "type":"adworkposition"
                            })
                        }
                    },
                    xhrFields: { withCredentials: true},
                    //配置返回数据格式
                    processResults: function (res) {
                        var opts = {
                            data: []
                        };
                        if (res.flag == 'success'){
                            $(res.data).each(function(i, _adworkposition) {
                                _adworkposition.audience_size = _adworkposition.coverage ? Kit.toThousands(_adworkposition.coverage) : null;
                                _adworkposition.type = 'work_positions';
                                _adworkposition.path = [I18N.getText('management', 'demographics'), I18N.getText('management', 'work'), I18N.getText('management', 'jobTitles')];
                                _adworkposition.parent = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'work') + " > " + I18N.getText('management', 'jobTitles');
                                //path: ["个人情况", "学历", "研究领域", "生物化学 （臨床化学）"]
                            })
                            opts.data = res.data;
                        }

                        return opts;
                    }
                }
                result.tip = I18N.getText('management', 'jobTitleTip')
            } else {
                ;
            }
            return result;
        }

        this.interestsSuggession = function(_sD, _interest, _locale){
            // http
            var par = {
                "interestsList":[_interest],
                "locale":_locale
            }

            http.work('/search/searchInterestSuggestion', par, 'GET').then(function(res){
                if(res.flag == 'success') {
                   var _suggestions = res.data;
                    var _ul = $(_sD).find("ul");
                    _ul.empty();
                    if (_suggestions && _suggestions.length){
                        var _li;
                        var selects = $(_sD).parents(".s-detail-area").data("selects");
                        selects = selects ? selects : [];
                        var isSelect;
                        $.each(_suggestions, function(i, _suggestion){
                            _suggestion.type = "interests";
                            if (selects.indexOf("" + _suggestion.type + "_" + _suggestion.id) > -1){
                                isSelect = true;
                            } else {
                                isSelect = false;
                            }

                            _li = $('<li class="suggestion-item"><button class="btn btn-default suggesstion-btn' + (isSelect ? ' disabled' : '') + '"><span>'+ _suggestion.name +'</span><br/><span>'
                            + (_suggestion.audienceSize ? Kit.toThousands(_suggestion.audienceSize) : 0 ) +'</span></button></li>');
                            _suggestion.path = I18N.getText('management', 'interests') + "#" + I18N.getText('management', 'additionalInterests');
                            _suggestion.path = _suggestion.path.replace(/\s/g,"");
                            _suggestion.type = "interests";
                            _suggestion.locale = _locale;
                            _li.data("info", _suggestion);
                            _ul.append(_li);
                        })
                    } else {
                        _ul.append('<li class="no-suggestion">' + I18N.getText('management', 'noAssociation') + '</li>')
                    }
                    $(_sD).removeClass("hide");
                }
            })
        }

        this.suggessionEvent = function(){
            var self = this;
            $(".edit-ad-container").off("click", ".suggestion-area li").on("click", ".suggestion-area li", function(e){
                e.preventDefault();
                e.stopImmediatePropagation();
                if ( $(this).find("button").hasClass("disabled")){
                    console.log("不可点击")
                    //不可点击
                    return false;
                }
                self.showGenerate();
                var _detail = $(e.target).parents(".s-detail-area").find(".detail");
                var _in = $(this).data("info");
                _detail.blend("selectDAT", [_in]);
                var _sDetailArea = $(this).parents(".s-detail-area")
                var selects = $(_sDetailArea).data("selects");
                selects = selects ? selects : [];
                selects.push("" + _in.type + "_" + _in.id);
                _sDetailArea.data("selects", selects);

                //继续联想
                self.interestsSuggession($(e.target).parents(".suggestion-area"), _in.name,  _in.locale);
            });

            //外面输入框focus时，如果有联想则显示联想
            $(".edit-ad-container").off("focus", ".blend-input").on("focus", ".blend-input", function(e){
                console.log("focus")
                var suggestionArea = $(this).parents(".s-detail-area").find(".suggestion-area");
                var suggestions = suggestionArea.find(".suggestion-item");
                if (suggestions && suggestions.length){
                    suggestionArea.removeClass("hide");
                }
            });
        }

        this.getSeldatas = function(_details) {
            var self = this;
            var selDatas = [];
            //兴趣
            if (_details.interests && _details.interests.length > 0) {
                //兴趣
                parserDetailItemWithId(selDatas, _details.interests, "interests", I18N.getText('management', 'interests') + " > " + I18N.getText('management', 'additionalInterests'),
                    [I18N.getText('management', 'interests'), I18N.getText('management', 'additionalInterests')]
                );
            }

            //更多类别
            if (_details.user_adclusters && _details.user_adclusters.length > 0) {
                //更多类别
                parserDetailItemWithId(selDatas, _details.user_adclusters, "user_adclusters", I18N.getText('management', 'moreCategories') + " > " + I18N.getText('management', 'facebookCategories'),
                    [I18N.getText('management', 'moreCategories'), I18N.getText('management', 'facebookCategories')]
                );
            }

            //行为 behaviors
            if (_details.behaviors && _details.behaviors.length > 0) {
                //行为
                parserDetailItemWithId(selDatas, _details.behaviors, "behaviors",I18N.getText('management', 'behaviors'),
                    [I18N.getText('management', 'behaviors')]
                );
            }

            //性取向
            if (_details.interested_in && _details.interested_in.length > 0) {
                //interested_in 性取向
                var _blockDatas = {
                    seldata : [],
                    selects : []
                }
                var _interested_ins = {
                    path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'relationship'), I18N.getText('management', 'interestedIn')],
                    type: "interested_in",
                    key: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn'),
                    tags: []
                };

                $.each(_details.interested_in, function (i, _interested_in) {
                    var _t;
                    var leaf = self.leafNodes["interested_in" + "_" + _interested_in];
                    if (leaf){
                        _t = leaf;
                        _t.type = "interested_in";
                    } else {
                        _t = {parent: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn'), type: "interested_in",
                            path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'relationship'), I18N.getText('management', 'interestedIn')]}
                        if (1 == _interested_in) {
                            //男性
                            _t.name = I18N.getText('management', 'men') ;
                            _t.id = 1;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn')
                                + " > " + I18N.getText('management', 'men');
                        } else if (2 == _interested_in) {
                            //未知
                            _t.name = I18N.getText('createAd', 'women');
                            _t.id = 2;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn')
                                + " > " + I18N.getText('createAd', 'women');;
                        } else if (3 == _interested_in) {
                            //未知
                            _t.name = I18N.getText('management', 'menAndWomen');
                            _t.id = 3;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn')
                                + " > " + I18N.getText('management', 'menAndWomen');
                        } else if (4 == _interested_in) {
                            //未知
                            _t.name = I18N.getText('management', 'unspecified');
                            _t.id = 4;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'interestedIn')
                                + " > " + I18N.getText('management', 'unspecified');;
                        }
                    }
                    _blockDatas.selects.push("" + _t.type + "_" + _t.id);
                    _interested_ins.tags.push(_t);
                });

                _blockDatas.seldata.push(_interested_ins);
                selDatas.push(_blockDatas);
            }

            //感情状况
            if (_details.relationship_statuses && _details.relationship_statuses.length > 0) {
                //relationship_statuses 感情状况
                var _blockDatas = {
                    seldata : [],
                    selects : []
                }
                var _relationship_statuses = {
                    path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'relationship'), I18N.getText('management', 'relationshipStatus')],
                    type: "relationship_statuses",
                    key: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus'),
                    tags: []
                };

                $.each(_details.relationship_statuses, function (i, _relationship_statuse) {
                    var leaf = self.leafNodes["relationship_statuses" + "_" + _relationship_statuse];
                    console.log(leaf)
                    var _t;
                    if (leaf){
                        _t = leaf;
                        _t.type = "relationship_statuses";
                    } else {
                        _t = {
                            parent: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus'),
                            type: "relationship_statuses",
                            path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'relationship'), I18N.getText('management', 'relationshipStatus')]
                        }
                        if (1 == _relationship_statuse) {
                            //男性
                            _t.name = I18N.getText('management', 'single');
                            _t.id = 1;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'single');
                        } else if (2 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'inARelationship');
                            _t.id = 2;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'inARelationship');
                        } else if (3 == _relationship_statuse) {
                            //未知
                            _t.name =  I18N.getText('management', 'married');
                            _t.id = 3;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " +  I18N.getText('management', 'married');
                        } else if (4 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'engaged');
                            _t.id = 4;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'engaged');
                        } else if (6 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'unspecified');
                            _t.id = 6;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'unspecified');
                        } else if (7 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'civilUnion');
                            _t.id = 7;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'civilUnion');
                        } else if (8 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'domesticPartnership');
                            _t.id = 8;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'domesticPartnership');
                        } else if (9 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'openRelationship');
                            _t.id = 9;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'openRelationship');
                        } else if (10 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'complicated');
                            _t.id = 10;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'complicated');
                        } else if (11 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'separated');
                            _t.id = 11;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'separated');
                        } else if (12 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'divorced');
                            _t.id = 12;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'divorced');
                        } else if (13 == _relationship_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'widowed');
                            _t.id = 13;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'relationship') + " > " + I18N.getText('management', 'relationshipStatus')
                                + " > " + I18N.getText('management', 'widowed');
                        }
                    }
                    _blockDatas.selects.push("" + _t.type + "_" + _t.id);
                    _relationship_statuses.tags.push(_t);
                });

                _blockDatas.seldata.push(_relationship_statuses);
                selDatas.push(_blockDatas);
            }


            //教育程度 education_statuses
            if (_details.education_statuses && _details.education_statuses.length > 0) {
                //教育程度 education_statuses
                var _blockDatas = {
                    seldata : [],
                    selects : []
                }
                var _education_statuses = {
                    path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'educationLevel')],
                    type: "education_statuses",
                    key: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel'),
                    tags: []
                };

                $.each(_details.education_statuses, function (i, _education_statuse) {
                    var leaf = self.leafNodes["education_statuses" + "_" + _education_statuse];
                    console.log(leaf)
                    var _t;
                    if (leaf){
                        _t = leaf;
                        _t.type = "education_statuses";
                    } else {
                        _t = {
                            parent: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'educationLevel'),
                            type: "education_statuses",
                            path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'educationLevel')]
                        }
                        if (1 == _education_statuse) {
                            _t.name = I18N.getText('management', 'inHighSchool');
                            _t.id = 1;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'inHighSchool');
                        } else if (2 == _education_statuse) {
                            _t.name =  I18N.getText('management', 'inCollege');
                            _t.id = 2;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'inCollege');
                        } else if (3 == _education_statuse) {
                            _t.name = I18N.getText('management', 'collegeGrad');
                            _t.id = 3;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'collegeGrad');
                        } else if (4 == _education_statuse) {
                            _t.name = I18N.getText('management', 'highSchoolGrad');
                            _t.id = 4;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'highSchoolGrad');
                        } else if (5 == _education_statuse) {
                            _t.name = I18N.getText('management', 'someCollege');
                            _t.id = 5;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'someCollege');
                        } else if (6 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'associateDegree');
                            _t.id = 6;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'associateDegree');
                        } else if (7 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'inGradSchool');
                            _t.id = 7;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'inGradSchool');
                        } else if (8 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'someGradSchool');
                            _t.id = 8;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'someGradSchool');
                        } else if (9 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'masteregree');
                            _t.id = 9;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'masteregree');
                        } else if (10 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'professionalDegree');
                            _t.id = 10;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') +" > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'professionalDegree');
                        } else if (11 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'doctorateDegree');
                            _t.id = 11;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'doctorateDegree');
                        } else if (12 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'unspecified1');
                            _t.id = 12;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'unspecified1');
                        } else if (13 == _education_statuse) {
                            //未知
                            _t.name = I18N.getText('management', 'someHighSchool');
                            _t.id = 13;
                            _t.key = I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'educationLevel')
                                + " > " + I18N.getText('management', 'someHighSchool');
                        }
                    }
                    _education_statuses.tags.push(_t);
                    _blockDatas.selects.push("" + _t.type + "_" + _t.id);
                });

                _blockDatas.seldata.push(_education_statuses);
                selDatas.push(_blockDatas);
            }

            //education_majors 研究领域  "education_majors"
            if (_details.education_majors && _details.education_majors.length > 0) {
                //研究领域
                parserDetailItemWithId(selDatas, _details.education_majors, "education_majors", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'fieldsOfStudy'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'fieldsOfStudy')]
                );
            }

            //education_schools 学校 education_schools
            if (_details.education_schools && _details.education_schools.length > 0) {
                parserDetailItemWithId(selDatas, _details.education_schools, "education_schools", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'schools'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'schools')]
                );
            }

            // 大学就读年份 "college_years":["2016","2017","2018","2019","2020"]
            if (_details.college_years && _details.college_years.length > 0) {
                //大学就读年份
                var _blockDatas = {
                    seldata : [],
                    selects : []
                }
                var _college_years = {
                    path: [I18N.getText('management', 'demographics'), I18N.getText('management', 'education'), I18N.getText('management', 'undergradYears')],
                    type: "college_years",
                    key: I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'education') + " > " + I18N.getText('management', 'undergradYears'),
                    start: 2016,
                    end: 2020
                };

                var start;
                var end;
                $.each(_details.college_years, function (i, _college_year) {
                    if (!start) {
                        start = Number(_college_year);
                    }

                    if (!end) {
                        end = Number(_college_year);
                    }

                    if (Number(_college_year) < start) {
                        start = Number(_college_year);
                    }

                    if (Number(_college_year) > end) {
                        end = Number(_college_year);
                    }
                });
                _blockDatas.selects.push("college_years");
                _college_years.start = start;
                _college_years.end = end;
                _blockDatas.seldata.push(_college_years);
                selDatas.push(_blockDatas);
            }

            // work_employers 雇主
            if (_details.work_employers && _details.work_employers.length > 0) {
                parserDetailItemWithId(selDatas, _details.work_employers, "work_employers", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'work') + " > " + I18N.getText('management', 'employers'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'work'), I18N.getText('management', 'employers')]
                );
            }

            //work_positions 职位
            if (_details.work_positions && _details.work_positions.length > 0) {
                parserDetailItemWithId(selDatas, _details.work_positions, "work_positions", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'work') + " > " + I18N.getText('management', 'jobTitles'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'work'), I18N.getText('management', 'jobTitles')]
                );
            }


            //industries 行业
            if (_details.industries && _details.industries.length > 0) {
                parserDetailItemWithId(selDatas, _details.industries, "industries", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'work') + " > " + I18N.getText('management', 'industries'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'work'), I18N.getText('management', 'industries')]
                );
            }

            //ethnic_affinity 族裔
            if (_details.ethnic_affinity && _details.ethnic_affinity.length > 0) {
                parserDetailItemWithId(selDatas, _details.ethnic_affinity, "ethnic_affinity", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'ethnicAffinity'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'ethnicAffinity')]
                );
            }

            //generation 世代
            if (_details.generation && _details.generation.length > 0) {
                parserDetailItemWithId(selDatas, _details.generation, "generation", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'generation'),
                     [I18N.getText('management', 'demographics'), I18N.getText('management', 'generation')]
                );
            }

            //family_statuses 父母 可以检查
            if (_details.family_statuses && _details.family_statuses.length > 0) {
                parserDetailItemWithId(selDatas, _details.family_statuses, "family_statuses", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'parents') + " > " + I18N.getText('management', 'allParents'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'parents'), I18N.getText('management', 'allParents')]
                );
            }

            //politics 政治（美国）
            if (_details.politics && _details.politics.length > 0) {
                parserDetailItemWithId(selDatas, _details.politics, "politics", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'politicsUS'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'politicsUS')]
                );
            }

            //life_events 生活纪事
            if (_details.life_events && _details.life_events.length > 0) {
                parserDetailItemWithId(selDatas, _details.life_events, "life_events", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'lifeEvents'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'lifeEvents')]
                );
            }

            //household_composition 住房条件
            if (_details.household_composition && _details.household_composition.length > 0) {
                parserDetailItemWithId(selDatas, _details.household_composition, "household_composition", I18N.getText('management', 'demographics') + " > " + I18N.getText('management', 'home') + " > " + I18N.getText('management', 'householdComposition'),
                    [I18N.getText('management', 'demographics'), I18N.getText('management', 'home'), I18N.getText('management', 'householdComposition')]
                );
            }

            function parserDetailItemWithId(selDatas, detailItems, _type, _ck, _cPath) {
                var _blockDatas = {
                    seldata: [],
                    selects: []
                }
                var seldBs = {};
                var _ck = _ck;

                var _key;
                $.each(detailItems, function (i, _detailItem) {
                    var leaf = self.leafNodes[_type + "_" + _detailItem.id];
                    if (leaf && leaf.parent) {
                        if (!seldBs[leaf.parent]) {
                            seldBs[leaf.parent] = {
                                path: leaf.path,
                                type: _type,
                                key: leaf.key,
                                tags: []
                            }
                        }
                        _key = leaf.parent;
                        _detailItem = leaf;
                    } else {
                        if (!seldBs[_ck]){
                            seldBs[_ck] =
                            {
                                path: _cPath,
                                type: _type,
                                key: _ck,
                                tags: []
                            };
                        }
                        _key = _ck;
                    }
                    _detailItem.type = _type;
                    _blockDatas.selects.push("" + _detailItem.type + "_" + _detailItem.id);
                    seldBs[_key].tags.push(_detailItem);
                });

                $.each(seldBs, function (i, seldB) {
                    _blockDatas.seldata.push(seldB);
                });

                selDatas.push(_blockDatas);
            }

            return selDatas;
        }

        this.renderGender = function(_condition, _originTargetingSpec){
            var _gender;
            if (!_originTargetingSpec.genders || _originTargetingSpec.genders.length == 0){
                //全部
                _gender = 0;
            } else {

                _gender = _originTargetingSpec.genders[0];
            }


            $('input[name="gender"][value="' + _gender + '"]').prop("checked", true).trigger("change", [true]);
        }

        function bidAmountLimit(_condition) {
            var _bidAmountRange = Kit.bidAmountRange(
                {
                    optimization_goal: $("div.ndp-drop-wrapper[name=optimization_goal]").data("val"),
                    billing_event: $("div.ndp-drop-wrapper[name=billing_event]").data("val")
                }, _condition ? _condition.priceLimit : undefined)
            var _bidamountPlaceholder;
            if (_bidAmountRange.max){
                _bidamountPlaceholder = I18N.getText('createAd', 'moneyRange',_bidAmountRange.min,_bidAmountRange.max);
            } else {
                _bidamountPlaceholder = I18N.getText('createAd', 'moneyRangeNoMax',_bidAmountRange.min);
            }
            return {bidamountPlaceholder : _bidamountPlaceholder, min : _bidAmountRange.min, max : _bidAmountRange.max};
        }

        this.renderBid = function(_adset, _condition){
            var self = this;
            //排期
            var _startTimeShow = moment(_adset.start_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            var _endTimeShow = ''
            if (_adset.end_utc_time){
                _endTimeShow = moment(_adset.end_utc_time).utcOffset(window.sessionStorage.timezoneValue).format('YYYY-MM-DD HH:mm');
            } else {
                _endTimeShow = I18N.getText('createAd', 'continuously');
            }
            $(".schedule").html(_startTimeShow + ' ~ ' + _endTimeShow);


            var _optimizationGoals = [];
            if (self.objective == 'MOBILE_APP_INSTALLS') { //应用安装
                _optimizationGoals = self.bidInfo.app;
            } else if (self.objective == 'WEBSITE_CLICKS') { //外链
                _optimizationGoals = self.bidInfo.outlink;
            }
            //optimization_goal
            var _optimizationGoalE = $("div.ndp-drop-wrapper[name=optimization_goal]").empty().drop({
                data:_optimizationGoals,
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE",function(e){
                //优化方向与收费方式联动
                var _sOptimizationGoal   = e.originalEvent.data.val;
                console.log(_sOptimizationGoal);

                var _index = Kit.keyIn(_optimizationGoals, _sOptimizationGoal, 'id');
                if (_index > -1){
                    var nB;
                    if(_sOptimizationGoal == 'APP_INSTALLS' && !self.cpaSupport)
                        nB = _optimizationGoals[_index].billingEventsNotSupportCpa;
                    else
                        nB = _optimizationGoals[_index].billingEvents;
                    $("div.ndp-drop-wrapper[name=billing_event]").empty().drop({
                        data:nB,
                        caret:"glyphicon-menu-right"
                    }).val(nB[0]);
                }
                //随着优化方向的变动，出价提示也会变更
                var _bidamountLimit = bidAmountLimit(_condition);
                $(".bidamount").find("input").attr("placeholder", _bidamountLimit.bidamountPlaceholder).attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
                $(".edit-ad-container").find( '.bidamount>input').trigger('keyup');
            });
            var _ioG = Kit.findBykey(_optimizationGoals, _adset.optimization_goal, 'id');
            _optimizationGoalE.val(_ioG)

            var initNB;
            if(_adset.optimization_goal == 'APP_INSTALLS' && !self.cpaSupport) {
                initNB = _ioG.billingEventsNotSupportCpa;
            } else {
                initNB = _ioG.billingEvents;
            }
            //billing_event
            $("div.ndp-drop-wrapper[name=billing_event]").empty().drop({
                data:initNB,
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE",function(e){
                 //随着出价方式的变动，出价提示也会变更
                var _bidamountLimit = bidAmountLimit(_condition);
                $(".bidamount").find("input").attr("placeholder", _bidamountLimit.bidamountPlaceholder).attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
                $(".edit-ad-container").find( '.bidamount>input').trigger('keyup');
            }).val(Kit.findBykey(_ioG.billingEvents, _adset.billing_event, 'id'));

            //budget_type
            var initBudgetType;
            var initBudget;
            if (_adset.daily_budget && _adset.daily_budget > 0){
                initBudgetType = {id: "daily_budget", text: I18N.getText('createAd', 'dailyBudget'), val: 'daily_budget' };
                initBudget = _adset.daily_budget;
            } else {
                initBudgetType = { id: "lifetime_budget", text: I18N.getText('createAd', 'lifetimeBudget'), val: 'lifetime_budget' }
                initBudget = _adset.lifetime_budget;
            }

            //设置预算
            $("div.ndp-drop-wrapper[name=budget_type]").drop({
                data: [
                    { id: "daily_budget", text: I18N.getText('createAd', 'dailyBudget'), val: 'daily_budget' },
                    { id: "lifetime_budget", text: I18N.getText('createAd', 'lifetimeBudget'), val: 'lifetime_budget' , disable : _adset.end_utc_time ? false:true}
                ],
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE", function(e){
                $(".edit-ad-container").find( '.budget>input').trigger('keyup');
            }).val(initBudgetType);

            $("div.ndp-sinput-wrapper[name=budget]").sinput({
                xion:"<span>$</span>",
                placeholder:I18N.getText('createAd', 'pleaseInputBudget'),
                pos:"left",//图标显示在左边  “left”, "right"
                default: Number(initBudget / 100).toFixed(2)
            });
            //预算精确到小数点两位
            $(".budget").find("input").numeral({ 'scale': 2 });

            //单价
            var _bidamountLimit = bidAmountLimit(_condition);
            var _bidamountE = $("div.ndp-sinput-wrapper[name=bidamount]").sinput({
                xion:"<span>$</span>",
                placeholder: _bidamountLimit.bidamountPlaceholder,
                pos:"left"//图标显示在左边  “left”, "right"
            });
            $("div.ndp-sinput-wrapper[name=bidamount]").find("input").attr("min", _bidamountLimit.min).attr("max", _bidamountLimit.max);
            var _initBid = '';
            if (_adset.is_autobid && _adset.is_autobid == true){
                $('input[name="autobid"][value="0"]').prop("checked", true).trigger("change");
            } else {
                $('input[name="autobid"][value="1"]').prop("checked", true).trigger("change");
                _initBid = Number(_adset.bid_amount/100).toFixed(2);
            }
            _bidamountE.val(_initBid);
            //单价精确到小数点两位
            $(".bidamount").find("input").numeral({ 'scale': 2 });


            //pacing_type
            var _initPacingType;
            if (!_adset.pacing_type || _adset.pacing_type.length == 0 || _adset.pacing_type.indexOf("standard") > -1){
                //标准
                _initPacingType = "standard";
            } else {
                //加速
                _initPacingType = "no_pacing";
            }
            $('input[name="pacing_type"][value="' + _initPacingType + '"]').prop("checked", true);
        }

        this.renderOther = function(){
            $("div.ndp-drop-wrapper[name=other]").drop({
                data:[{name :  I18N.getText('management', 'customAudiences'), val : 'custom-audience-area'},{name : I18N.getText('createAd', 'languages'), val : 'locales-area'}],
                type:6,
                selectOnClose : false,
                caret:"glyphicon-menu-right"
            }).on("ITEM_CLICK",function(e){
                var _t   = e.originalEvent.data.val;
                $("." + _t).toggleClass("hide");
            }).val(I18N.getText('createAd', 'addOtherCondition'))
        }

        this.renderConnection = function(_accountId, _originTargetingSpec){
            $(".connection").select2({
                data: [],
                placeholder: I18N.getText('management', 'pleaseAdd'),
                multiple: true,
                allowClear: false,
                width: '100%',
            });

            //渲染关系
            var par = {
                fb_account_id : _accountId
            }
            http.work('/connectionobjects/searchConnectionobjects', par, 'POST').then(function(res){
                if(res.flag == 'success') {
                    var objects = res.data;
                    var datas = [];
                    $.each(objects, function(i, _object){
                        if (_object.type == 2 || _object.type == 1|| _object.type == 3){
                            _object.id = _object.fbConnectionObjectId;
                            _object.text = _object.name;
                            datas.push(_object);
                        }
                    });

                    $(".connection").select2({
                        data: datas,
                        placeholder: I18N.getText('management', 'pleaseAdd'),
                        multiple: true,
                        allowClear: false,
                        width: '100%',
                        templateResult : function(_object){
                            var _type = '';
                            if (_object.type == 2){
                                _type = I18N.getText('management', 'app');
                            } else if (_object.type == 1){
                                _type = I18N.getText('management', 'page');
                            } else if (_object.type == 3){
                                _type = I18N.getText('management', 'event');
                            } else {
                                ;
                            }
                            return  $('<div><span>'+ _object.name + '</span><span class="connection-type">'+ _type + '</span>');
                        }
                    }).on("select2:select", function(e){
                        self.showGenerate();
                    }).on("select2:unselect", function(e){
                        self.showGenerate();
                    });

                    $(".connections").on("select2:select", function(e){
                        //联系和排除需要相冲突
                        var _id = e.params.data.id;
                        var finalData = [];
                        var _el = $(".excluded_connections");
                        var _oDatas = _el.select2("data");
                        $.each(_oDatas, function(i, _oData){
                            if (_oData.id != _id){
                                finalData.push(_oData)
                            }
                        });
                        _el.select2("data", finalData);
                    });
                    $(".excluded_connections").on("select2:select", function(e){
                        //联系和排除需要相冲突
                        var _id = e.params.data.id;
                        var finalData = [];
                        var _el = $(".connections");
                        var _oDatas = _el.select2("data");
                        $.each(_oDatas, function(i, _oData){
                            if (_oData.id != _id){
                                finalData.push(_oData)
                            }
                        });
                        _el.select2("data", finalData);
                    });
                }
            }).done(function() {
                //回填
                var _initConnections = _originTargetingSpec.connections;
                var _initExcludedConnections = _originTargetingSpec.excluded_connections;
                var _initFriendsOfConnections = _originTargetingSpec.friends_of_connections;

                if ((_initConnections && _initConnections.length > 0)
                    || (_initExcludedConnections && _initExcludedConnections.length > 0)
                    || (_initFriendsOfConnections && _initFriendsOfConnections.length > 0)){

                    $('input[name="connection"]').prop("checked", true);
                    $('input[name="connection"]').trigger("change", [true]);

                    if (_initConnections && _initConnections.length > 0){
                        fillConnections(_initConnections, $(".connections"));
                    }
                    if (_initExcludedConnections && _initExcludedConnections.length > 0){
                        fillConnections(_initExcludedConnections, $(".excluded_connections"));
                    }
                    if (_initFriendsOfConnections && _initFriendsOfConnections.length > 0){
                        fillConnections(_initFriendsOfConnections, $(".friends_of_connections"));
                    }
                } else {
                    //todo 需要获取当前应用的信息
                    fillConnections([{"id" : "", "name" : ""}], $(".excluded_connections"));
                }

                function fillConnections(_cDatas, _dom){
                    $.each(_cDatas, function(i, _cData){
                        _cData.text = _cData.name;
                    });

                    _dom.select2("data", _cDatas)
                }
            });


        }

        //this.renderAge = function(_originTargetingSpec){
        //    var min_age = 13;
        //    var max_age = 65;
        //    var c_min_age = min_age;
        //    var c_max_age = max_age;
        //    var min_ages = [];
        //    var max_ages = [];
        //    for (var i = min_age; i <= max_age; i++){
        //        var _i = {val : i};
        //        if (i < c_min_age || i > c_max_age){
        //            _i.disable = true;
        //            _i.name = i + "(" + I18N.getText('management', 'limitByProductManagement') + ")"
        //        } else {
        //            _i.name = i;
        //        }
        //
        //        min_ages.push(_i);
        //        max_ages.push(_i);
        //    }
        //
        //    var _initMinAge = _originTargetingSpec.age_min  ? _originTargetingSpec.age_min : min_age;
        //    var _initMaxAge = _originTargetingSpec.age_max ? _originTargetingSpec.age_max  : max_age;
        //    var _minDrop = $("div.ndp-drop-wrapper[name=min-age]").drop({
        //        data:min_ages,
        //        caret:"glyphicon-menu-right"
        //    }).on("ITEM_CHANGE",function(e){
        //        self.showGenerate();
        //    }).on("ITEM_CLICK",function(e){
        //        var c_mi  = e.originalEvent.data.val;
        //        var c_mx  =  $("div.ndp-drop-wrapper[name=max-age]").data("val");
        //        if (c_mx < c_mi){
        //            _maxDrop.val({name :  c_mi , val : c_mi});
        //        }
        //    });
        //    _minDrop.val({name : _initMinAge , val : _initMinAge});
        //
        //   var _maxDrop =  $("div.ndp-drop-wrapper[name=max-age]").drop({
        //        data:max_ages,
        //        caret:"glyphicon-menu-right"
        //    }).on("ITEM_CHANGE",function(e){
        //       self.showGenerate();
        //   }).on("ITEM_CLICK",function(e){
        //        var c_mx   = e.originalEvent.data.val;
        //        var c_mi  =  $("div.ndp-drop-wrapper[name=min-age]").data("val");
        //        if (c_mx < c_mi){
        //            _minDrop.val({name :  c_mx , val : c_mx});
        //        }
        //    });
        //    _maxDrop.val({name :  _initMaxAge , val : _initMaxAge});
        //}

        this.countLocation = function(){
            var self = this;
            var flag = true;
            var locations = $(".location-select2").select2("data");
            if (locations.length > 25){
                flag = false;
                $(".edit-tip").addClass("location-tip");
                self.showDangerTip("danger", I18N.getText("management", "locationLimit",  25, locations.length));
            } else {
                $(".location-tip").empty();
                $(".edit-tip").removeClass("location-tip");
            }
            return flag;
        }
        this.renderLocation = function(_condition, _originTargetingSpec){
            var self = this;
            var _isClude = 1;
            $("div.ndp-drop-wrapper[name=location-clude]").drop({
                data:[{name : I18N.getText('management', 'include'), val : '1'},{name : I18N.getText('management', 'exclude'), val :'0'}],
                caret:"glyphicon-menu-right"
            }).on("ITEM_CLICK",function(e){
                _isClude = e.originalEvent.data.val;
            }).val({name : I18N.getText('management', 'include'), val : '1'})

            var _cType = 'country';
            $("div.ndp-drop-wrapper[name=location-type]").drop({
                data:[{name : I18N.getText('management', 'country'), val : 'country'},{name : I18N.getText('management', 'all1'), val : 'all'}],
                caret:"glyphicon-menu-right"
            }).on("ITEM_CLICK",function(e){
                _cType = e.originalEvent.data.val;
            }).val({name : I18N.getText('management', 'country'), val : 'country'})

            var _cType = 'country';
            //$('.location').select2({
            //    placeholder:  I18N.getText('management', 'addLocations'),
            //    multiple: true,
            //    allowClear: false,
            //    width: '100%',
            //    minimumInputLength: 1,
            //    ajax:{
            //        type:'POST',
            //        url: cors_config.api_host + '/search/searchAdgeolocation',
            //        dataType: 'json',
            //        delay: 250,
            //        data: function (query) {
            //            return{
            //                param:JSON.stringify({
            //                    q: query.term,
            //                    locale: I18N.language,
            //                    cType: _cType
            //                })
            //            }
            //        },
            //        xhrFields: {
            //            withCredentials: true
            //        },
            //        //配置返回数据格式
            //        processResults: function (res) {
            //            var opts = {
            //                results: []
            //            };
            //            var data = res.data;
            //            $(data).each(function(i, v) {
            //                var _countryCode = v.countryCode || v.country_code;
            //                if (v.type == 'country'){
            //                    v.id = _countryCode;
            //                    v.text = v.name;
            //                } else {
            //                    v.id = v.key;
            //                    v.text = v.name + '(' + _countryCode +')';
            //                }
            //                v.isClude = _isClude;
            //
            //                if (self.locationIncludeKeys.length && self.locationIncludeKeys.indexOf(v.id) == -1){
            //                    v.disabled = 'disabled';
            //                    v.isNotInclude = true;
            //                }
            //
            //                if (self.locationExcludeKeys.indexOf(v.id) == -1){
            //                    //不属于不投放就显示
            //                    opts.results.push(v);
            //                }
            //            });
            //            return opts;
            //        },
            //        cache: false
            //    },
            //    templateResult : function(_location){
            //         if (_location.isNotInclude){
            //             return $('<span>' + _location.text +'</span><span class="location-r">' + I18N.getText('management', 'onlyRegion')  +'</span>');
            //         } else {
            //             return _location.text;
            //         }
            //    },
            //    templateSelection : function(_location){
            //        var _text = ''
            //        var _countryCode = _location.countryCode || _location.country_code || _location.country;
            //        if (_location.type == 'country'){
            //            _text = _location.name;
            //         } else if (_location.type == 'region'){
            //            _text = _location.name + '(' + _countryCode +')';
            //         } else if (_location.type == 'city'){
            //            if (_location.radius && _location.radius > 0){
            //                _text = _location.name + '+ ' + _location.radius + (_location.distance_unit ? _location.distance_unit : I18N.getText('management', 'kilometer')) + '(' + _countryCode +')';
            //            } else {
            //                _text = _location.name + '(' + _countryCode +')';
            //            }
            //
            //         } else if (_location.type == 'zip'){
            //            _text = _location.name + '(' + _countryCode +')';
            //         } else if (_location.type ==  'electoral_district'){
            //            _text = _location.name + '(' + _countryCode +')';
            //         } else if (_location.type == 'geo_market'){
            //            _text = _location.name + ',DMA®' + '(' + _countryCode +')'
            //         } else if (_location.type ==  'custom_location'){
            //            _text = '(' +  _location.latitude + ',' + _location.longitude + ')' +  '+ ' + _location.radius +(_location.distance_unit ? _location.distance_unit : I18N.getText('management', 'kilometer')) + '(' + _countryCode +')';
            //        }
            //
            //        return _text  + '[' + (_location.isClude == 1 ? I18N.getText('management', 'include') :I18N.getText('management', 'exclude'))+ ']';
            //    }
            //}).off("select2:unselect").on("select2:unselect",function(e){
            //    var o = e.params.data;
            //    $(".location").find("option[value="+o.id+"]").remove();
            //    self.countLocation();
            //    self.showGenerate();
            //}).off("select2:select").on("select2:select",function(e){
            //    self.showGenerate();
            //    self.countLocation();
            //}).on("select2:open",function(){
            //    //地区支持粘贴
            //    self.bindCopyToLocation($(this).closest('.location-area'));  //绑定copy事件
            //});
            userAudienceKit.initLocation({
                locationArea: $(".location-area"),
                changeCallBack: function () {
                    self.showGenerate();
                    self.countLocation();
                },
                locationIncludeKeys: self.locationIncludeKeys,
                locationExcludeKeys: self.locationExcludeKeys
            });

            //渲染选区
            self.renderLocationS(_condition);

            //渲染地区类型
            var _locationTypesE = $("div.ndp-drop-wrapper[name=location_types]").drop({
                data:[{name :  I18N.getText('createAd', 'peopleAllHere'), val : '1'},{name : I18N.getText('createAd', 'peopleLiveInHere'), val : '2'},
                    {name : I18N.getText('createAd', 'peopleRecentlyHere'), val : '3'},{name : I18N.getText('createAd', 'peopleTravelingHere'), val : '4'}],
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE",function(e){
                self.showGenerate();
            })

            //回填地区类型
            if (_originTargetingSpec.geo_locations && _originTargetingSpec.geo_locations.location_types && _originTargetingSpec.geo_locations.location_types.length > 0){
                var _initLocationTypes = _originTargetingSpec.geo_locations.location_types;
                if (_initLocationTypes.length > 1){
                    _locationTypesE.val({name : I18N.getText('createAd', 'peopleAllHere'), val : '1'});
                } else {
                    if (_initLocationTypes[0] == 'home'){
                        _locationTypesE.val({name : I18N.getText('createAd', 'peopleLiveInHere'), val : '2'});
                    }

                    if (_initLocationTypes[0] == 'recent'){
                        _locationTypesE.val({name : I18N.getText('createAd', 'peopleRecentlyHere'), val : '3'});
                    }

                    if (_initLocationTypes[0] == 'travel_in'){
                        _locationTypesE.val({name : I18N.getText('createAd', 'peopleTravelingHere'), val : '4'});
                    }
                }
            } else {
                _locationTypesE.val({name :  I18N.getText('createAd', 'peopleAllHere'), val : '1'});
            }

            //回填地区
            if (_originTargetingSpec.geo_locations || _originTargetingSpec.excluded_geo_locations){
                //回填地区
                var _initLocations = [];
                //包含
                self.fillLocations(_originTargetingSpec.geo_locations, _initLocations, 1)

                //不包含
                self.fillLocations(_originTargetingSpec.excluded_geo_locations, _initLocations, 0);
                $('.location-select2').select2("data", _initLocations);
            }
        }

        this.fillLocations = function(_locations, _initLocations, _isClude){
            if (!_locations){
                return;
            }

            //国家
            if (_locations.countries){
                $.each(_locations.countries, function(i, _initCountry){

                    if ( typeof(_initCountry) == "object" ){
                        _initCountry.id = _initCountry.country_code;
                        _initCountry.text = _initCountry.name;
                        _initCountry.isClude = _isClude;
                        _initCountry.type = "country";
                        _initLocations.push(_initCountry);
                    } else {
                        var _initCountrys = {}
                        _initCountrys.id = _initCountry;
                        _initCountrys.text = _initCountry;
                        _initCountrys.name = _initCountry;
                        _initCountrys.isClude = _isClude;
                        _initCountrys.type = "country";
                        console.log(_initCountrys)
                        _initLocations.push(_initCountrys);
                    }
                })
            }

            //regions
            if (_locations.regions){
                $.each(_locations.regions, function(i, _initRegion){
                    _initRegion.id = _initRegion.key;
                    _initRegion.text = _initRegion.name;
                    _initRegion.isClude = _isClude;
                    _initRegion.type = "region";
                    _initLocations.push(_initRegion);
                })
            }

            //城市
            if (_locations.cities){
                $.each(_locations.cities, function(i, _initCity){
                    _initCity.id = _initCity.key;
                    _initCity.text = _initCity.name;
                    _initCity.isClude = _isClude;
                    _initCity.type = "city";
                    _initLocations.push(_initCity);
                })
            }

            //邮编 zip
            if (_locations.zips){
                $.each(_locations.zips, function(i, _initZip){
                    _initZip.id = _initZip.key;
                    _initZip.text = _initZip.name;
                    _initZip.isClude = _isClude;
                    _initZip.type = "zip";
                    _initLocations.push(_initZip);
                })
            }

            //geo_market
            if (_locations.geo_markets){
                $.each(_locations.geo_markets, function(i, _initGeoMarket){
                    _initGeoMarket.id = _initGeoMarket.key;
                    _initGeoMarket.text = _initGeoMarket.name;
                    _initGeoMarket.isClude = _isClude;
                    _initGeoMarket.type = "geo_market";
                    _initLocations.push(_initGeoMarket);
                })
            }

            //electoral_district 国会
            if (_locations.electoral_districts){
                $.each(_locations.electoral_districts, function(i, _initElectoralDistrict){
                    _initElectoralDistrict.id = _initElectoralDistrict.key;
                    _initElectoralDistrict.text = _initElectoralDistrict.name;
                    _initElectoralDistrict.isClude = _isClude;
                    _initElectoralDistrict.type = "electoral_district";
                    _initLocations.push(_initElectoralDistrict);
                })
            }

            //自定义地图
            if (_locations.custom_locations){
                $.each(_locations.custom_locations, function(i, _initCustomLocation){
                    _initCustomLocation.id = _initCustomLocation.latitude + "_" + _initCustomLocation.longitude;
                    _initCustomLocation.text = _initCustomLocation.name;
                    _initCustomLocation.isClude = _isClude;
                    _initCustomLocation.type = "custom_location";
                    _initLocations.push(_initCustomLocation);
                })
            }
        }
        this.renderLocationS = function(_condition, _isClude){
            if (!_condition){
                return;
            }

            $(".c-location").removeClass("hide");
            var _magicContent = $(".magic-content");
            var _regionType = _condition.regionAndPrices.include && _condition.regionAndPrices.include.length > 0 ? 'include'  : 'global';
            _magicContent.attr("type", _regionType);
            if (_regionType == 'include'){
                var inData = _condition.regionAndPrices.include;
                //指定
                $.each(inData, function(i, _in){
                    var hd = $("<h4><label class='loaction-s-b'><input type='checkbox'>"+ I18N.getText('createAd', 'unitPrice') +" $"+_in.price+"</label></h4>");
                    _magicContent.append(hd);

                    (function(hd){
                        hd.find("input[type]").unbind("change").change(function(e){
                            e.stopImmediatePropagation();
                            if($(this).prop("checked")){
                                $(this).parents("h4").next("ul").find("input[type]").prop("checked",true);
                            }else{
                                $(this).parents("h4").next("ul").find("input[type]").prop("checked",false);
                            }
                        });
                    }(hd));
                    var arr = _in.region;
                    var ul = $("<ul data-type='include'>");
                    for(var n=0;n<arr.length;n++){
                        var o = arr[n];
                        if(!o) continue;
                        var title = o.type||o.cType||"country";
                        var id = o.key||o.countryCode;
                        var text;
                        if(title == 'country'){
                            text = o.name + '('+id+ ')'
                        } else {
                            text =  o.name;
                        }
                        var li = $("<li data-value="+id+" data-title="+title+" country-code='" + o.countryCode  + "' c-name='" + o.name + "'>\
                               <label><input type='checkbox' value='" +  id + "'  data-title='" + title  + "' c-name='" + o.name + "' >"+text+"</label></li>");
                        ul.append(li);
                    }
                    _magicContent.append(ul);
                })
            } else {
                //全球
                $.each(Global, function(key, arr) {
                    var hd = $("<span class='loaction-s-b'>"+(key=="location"? I18N.getText('createAd', 'accordingAddress'): I18N.getText('createAd', 'accordingLanguage'))+"</span>");
                    _magicContent.append(hd);
                    var ul = $("<ul data-type='global'>");
                    for(var j=0;j<arr.length;j++){
                        var o = arr[j];
                        var id = o.key||o.countryCode;
                        var li = $("<li data-value="+id+" data-title='country'>\
                               <label><input type='checkbox' data-title='country' value='" +  id + "' key='" +  key + "'>"+o.name+"</label></li>");
                        ul.append(li);
                    }
                    _magicContent.append(ul);
                })
            }
        },
        /*
         地址区域绑定复制功能
         select2 4.0 DataAdapter 报错 引用full.min.js同样出错
         select2 4.0 对keydown有清除冒泡动作 所以需要延时绑定keydown  用托管事件不起作用
         select2 4.0 unselect事件对原事件可能有销毁  需要在unselect 后再次进行绑定keydown
         触发事件源：select2:open  原因是该插件的展示时后销毁原input dom，且无法将事件代理至 .only-lb
         * */
        this.bindCopyToLocation = function(onlyLB){
            var self = this;
            var isCtrlKey   = false,		 //用于处理copy监控偶发性失效问题
                isLoading   = false;		 //用于处理重复粘贴

            //禁用鼠标右键粘贴
            onlyLB.off('contextmenu');
            onlyLB.on('contextmenu', function(e){
                e.stopPropagation()
                return false;
            });
            //判定是否为copy操作。触发时间在select2.query之前
            $('.select2-search__field', onlyLB).off('keydown');
            $('.select2-search__field', onlyLB).on('keydown', function(e){
                if(e.ctrlKey|| e.metaKey){
                    isCtrlKey = true;
                }
            });

            //绑定copy事件。触发时间在select2.query之后
            onlyLB.off('keyup');
            onlyLB.on('keyup',function(e){
                var onlyLB =$(this),
                    loc = $('.location-select2', this);
                if(!isLoading && isCtrlKey && e.keyCode == 86){
                    var par = {
                        countries: $('.select2-search__field', this).val() || '',
                        locale:I18N.language
                    };
                    isLoading = true;
                    Kit.loading.show(onlyLB);
                    loc.select2('close');
                    http.work('/search/searchAdgeolocationList', par, 'POST').then(function(res){
                        if(res.flag == 'success'){
                            if (res.data.length != 0 ){
                                var preload_data = loc.select2('data'),
                                    _region = [];
                                $.each(preload_data, function(i, v) {
                                    _region.push(v);
                                });

                                var isChange = false;
                                $.each(res.data,function(i,v){
                                    //去除重复的国家
                                    var index = Kit.keyIn(_region, v.countryCode, "id");
                                    if (index == -1){
                                        isChange = true;
                                        v.id = v.countryCode;
                                        v.text = v.name + '('+ v.countryCode +')';
                                        v.isClude = $("div.ndp-drop-wrapper[name=location-clude]").data("val");
                                        _region.push(v);
                                    }
                                });

                                loc.select2('data', _region);
                                if (isChange){
                                    self.countLocation();
                                    self.showGenerate();
                                }
                            }
                        }
                        isLoading = false;
                        Kit.loading.hide(onlyLB);
                    });
                }
                window.setTimeout(function(){
                    isCtrlKey = false;
                },300);
                return false;
            });

        }
        this.renderOs = function(_condition, _originTargetingSpec){
            var self = this;
            var android = [{name : "2.0", val: "2.0"},
                {name : "2.1", val: "2.1"},
                {name : "2.2", val: "2.2"},
                {name : "2.3", val: "2.3"},
                {name : "3.0", val: "3.0"},
                {name : "3.1", val: "3.1"},
                {name : "3.2", val: "3.2"},
                {name : "4.0", val: "4.0"},
                {name : "4.1", val: "4.1"},
                {name : "4.2", val: "4.2"},
                {name : "4.3", val: "4.3"},
                {name : "4.4", val: "4.4"},
                {name : "5.0", val: "5.0"},
                {name : "5.1", val: "5.1"},
                {name : "6.0", val: "6.0"}
            ];
            var ios = [{name : "2.0", val: "2.0"},
                {name : "3.0", val: "3.0"},
                {name : "4.0", val: "4.0"},
                {name : "4.3", val: "4.3"},
                {name : "5.0", val: "5.0"},
                {name : "6.0", val: "6.0"},
                {name : "7.0", val: "7.0"},
                {name : "7.1", val: "7.1"},
                {name : "8.0", val: "8.0"},
                {name : "8.1", val: "8.1"},
                {name : "8.2", val: "8.2"},
                {name : "8.3", val: "8.3"},
                {name : "8.4", val: "8.4"},
                {name : "9.0", val: "9.0"},
                {name : "9.1", val: "9.1"},
                {name : "9.2", val: "9.2"}
            ];

            var userOs = _originTargetingSpec.user_os;
            var _userOsOne = userOs[0];
            var _s = _userOsOne.split('_');
            var _type = _s[0];
            self.osType = _type;
            var osData = _type == 'iOS' ? ios : android;
            var minVal = _s[2] ? _s[2] : osData[0].value;
            var maxVal = _s[3] && _s[3] == 'to' ? {name: _s[4], val : _s[4]} : {name: I18N.getText('management', 'none'), val : '-1'};

            $(".os-type").html(_type);
            $("div.ndp-drop-wrapper[name=min-os]").drop({
                data:osData,
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE",function(e){
                self.showGenerate();
            }).on("ITEM_CLICK",function(e){
                var _data = e.originalEvent.data.val;
                $.each($("div.ndp-drop-wrapper[name=max-os]").find(".drop-one-item"), function(i, _item){
                    if ($(_item).attr("value") < _data){
                        $(_item).addClass("disabled");
                    } else {
                        $(_item).removeClass("disabled");
                    }
                })
            }).val(minVal);

            osData.unshift({name : I18N.getText('management', 'none'), val: "-1"})
            $("div.ndp-drop-wrapper[name=max-os]").drop({
                data:osData,
                caret:"glyphicon-menu-right"
            }).on("ITEM_CHANGE",function(e){
                self.showGenerate();
            }).val(maxVal);


        }

        this.renderDevice = function(_condition, _originTargetingSpec){
            $(".device").select2({data : [],placeholder: I18N.getText('management', 'enterDeviceName'), width: '100%', multiple: true,
                allowClear: false,});

            //渲染设备下来选项
            var par = {
                "locale" : I18N.language,
                "classT" : "user_device"
            }

            http.work('/search/searchFbAdTargetingCategory', par, 'POST').then(function(res){
                if(res.flag == 'success') {
                    var _allUserDevices = res.data;
                    var datas = [];
                    $.each(_allUserDevices, function(i, _allUserDevice){
                        if (self.osType == _allUserDevice.platform){
                            _allUserDevice.id = _allUserDevice.name;
                            _allUserDevice.text =_allUserDevice.description;
                            datas.push(_allUserDevice)
                        }
                    });

                    $(".device").empty().select2({
                        data: datas,
                        placeholder:  I18N.getText('management', 'enterDeviceName'),
                        multiple: true,
                        allowClear: false,
                        width: '100%'
                    }).on("select2:select", function(){
                        self.showGenerate();
                    }).on("select2:unselect", function(){
                        self.showGenerate();
                    });
                }
            }).done(function() {
                //回填
                var _initUserDevices = _originTargetingSpec.user_device;
                if (_initUserDevices){
                    $.each(_initUserDevices, function(i, _initUserDevice){
                        _initUserDevice.id = _initUserDevice.name;
                        _initUserDevice.text = _initUserDevice.description;
                    });

                    $('.device').select2('data',_initUserDevices);
                }
            });
        }

        this.renderWireless = function(_condition, _originTargetingSpec){
            if (_originTargetingSpec.wireless_carrier && _originTargetingSpec.wireless_carrier.length > 0 && _originTargetingSpec.wireless_carrier[0] == "Wifi"){
                $('input[name="wireless"][value="1"]').prop("checked", true);
            } else {
                $('input[name="wireless"][value="0"]').prop("checked", true);
            }
        }

        this.renderPageType = function(result){
            var _originTargetingSpec = result.targeting_spec;
            var self = this;
            if (self.objective != 'MOBILE_APP_INSTALLS') { //应用安装
                $(".website").removeClass("hide");
            }


            $.each(_originTargetingSpec.page_types, function(i, _pageType){
                $('input[name="page-type"][value="' + _pageType + '"]').prop("checked", true);
            });

            //todo instagram   evan 2016-03-24 沟通后：两步 一：pagetype赋值，二：我们是否支持
            if(result.instagram_support){
                return;
            }
            var $ins = $('input[name="page-type"][value="instagramstream"]');
            $ins.addClass('disabled').attr("disabled",true);
            $ins.parent().append(I18N.getText('management','unboundAccount'));
        }

        this.renderLocales = function(_originTargetingSpec){
            $('.locales').select2({
                placeholder:I18N.getText('management', 'enterLanguage'),
                multiple: true,
                allowClear: false,
                width: '100%',
                minimumInputLength: 1,
                ajax:{
                    type:'POST',
                    url: cors_config.api_host + '/search/searchAdlocale',
                    dataType: 'json',
                    delay: 50,
                    data: function (query) {
                        return{
                            param:JSON.stringify({
                                type:"adlocale",
                                q: query.term,
                                locale: I18N.language
                            })
                        }
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    //配置返回数据格式
                    processResults: function (res, param) {
                        var opts = {
                            results: []
                        };
                        var data = res.data;
                        $(data).each(function(i, v) {
                            opts.results.push({
                                id : v.key,
                                text: v.name
                            })
                        });
                        return opts;
                    },
                    cache: false
                }
            }).on("select2:select", function(){
                self.showGenerate();
            }).on("select2:unselect", function(){
                self.showGenerate();
            });

            if (_originTargetingSpec.locales){
                $.each(_originTargetingSpec.locales, function(i, _initLacale){
                    _initLacale.id = _initLacale.key;
                    _initLacale.text = _initLacale.name;
                });
                $('.locales').select2("data", _originTargetingSpec.locales);
            }
        }

        this.renderCustomAudience = function(_originTargetingSpec){
            var self = this;
            $("div.ndp-drop-wrapper[name=custom-audience-clude]").drop({
                data:[{name : I18N.getText('management', 'include'), val : '1'},{name :I18N.getText('management', 'exclude'), val :'0'}],
                caret:"glyphicon-menu-right"
            }).val({name : I18N.getText('management', 'include'), val : '1'})

            $(".custom-audience").select2({
                placeholder: I18N.getText('management', 'chooseCustomAudience'),
                data : [],
                width: '100%',
                multiple: true,
                allowClear: false
            });

            //渲染设备下来选项
            var par = {
                "account_id" : self.adSet.account_id,
            }

            http.work('/customaudiencetemplate/getCustomAudienceListByFbAccount', par, 'GET').then(function(res){
                if(res.flag == 'success') {
                    if (!res.data){
                        return;
                    }
                    var _allCustomAudiences = res.data;
                    //_allCustomAudiences = [{id : 1 , name : 'test1'},{id : 2 , name : 'test2'}]
                    var datas = [];
                    $.each(_allCustomAudiences, function(i, _allCustomAudience){
                        _allCustomAudience.id = _allCustomAudience.id;
                        _allCustomAudience.text =_allCustomAudience.name;
                        datas.push(_allCustomAudience)
                    });

                    $(".custom-audience").select2({
                        data: datas,
                        placeholder: I18N.getText('management', 'chooseCustomAudience'),
                        multiple: true,
                        allowClear: false,
                        width: '100%',
                        templateSelection : function(_customAudience){
                            return _customAudience.name  + '[' + (_customAudience.isClude == 1  || _customAudience.isClude == "1" ? I18N.getText('management', 'include') : I18N.getText('management', 'exclude'))+ ']';
                        }
                    }).off("select2:unselect").on("select2:unselect",function(e){
                        self.showGenerate();
                    }).off("select2:select").on("select2:select",function(e){
                        var selects = $(".custom-audience").select2("data");
                        var o = e.params.data
                        var index = Kit.keyIn(selects, o.id, "id")
                        if (index > -1) {
                            selects[index]["isClude"] = $("div.ndp-drop-wrapper[name=custom-audience-clude]").data("val");
                            $(".custom-audience").select2("data", selects);
                        }
                        self.showGenerate();
                    });
                }
            }).done(function() {
                //回填
                var _initCustomAudiences = [];
                //包含
                fillCustomAudiences(_originTargetingSpec.custom_audiences, 1);
                //不包含
                fillCustomAudiences(_originTargetingSpec.excluded_custom_audiences, 0)
                $('.custom-audience').select2('data',_initCustomAudiences);

                function fillCustomAudiences(_custom_audiences, _isClude){
                    if (!_custom_audiences){
                        return;
                    }
                    var _cs = $(".custom-audience");
                    $.each(_custom_audiences, function(i, _initCustomAudience){
                        _initCustomAudience.id = _initCustomAudience.id;
                        _initCustomAudience.text = _initCustomAudience.name;
                        _initCustomAudience.isClude = _isClude
                        _initCustomAudiences.push(_initCustomAudience);
                        _cs.find("option[value='" +  _initCustomAudience.id  +  "']").remove();
                    });

                }
            });
        }


        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusOK
         * @param      {<type>}  result  { description }
         */
        this.queryStatusOK = function(result) {
            console.info(result)
            self.$el.sidepanel('hide');
        }

        /**
         * { 查询job执行成功后的回调 }
         *
         * @method     queryStatusFail
         * @param      {<type>}  result  { description }
         */
        this.queryStatusFail = function(result) {
            console.info(result)
        }


        /**
         * 字典
         */
        this.bidInfo = {
            "outlink": [{
                id: "LINK_CLICKS",
                text: I18N.getText('createAd', 'websiteLinkClicks'),
                val: "LINK_CLICKS",
                billingEvents: [
                    { id: "LINK_CLICKS", text:  I18N.getText('createAd', 'linkClicks'), val: "LINK_CLICKS" },
                    { id: "IMPRESSIONS", text:I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" }
                ]
            }, {
                id: "IMPRESSIONS",
                text:I18N.getText('createAd', 'impressions'),
                val: "IMPRESSIONS",
                billingEvents: [
                    { id: "IMPRESSIONS", text: I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" }
                ]
            }, {
                id: "REACH",
                text: I18N.getText('createAd', 'dailyUniqueReach'),
                val: "REACH",
                billingEvents: [
                    { id: "IMPRESSIONS", text: I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" }
                ]
            }],
            "app": [{
                id: "APP_INSTALLS",
                text: I18N.getText('createAd', 'appInstalls'),
                val: "APP_INSTALLS",
                billingEvents: [
                    { id: "IMPRESSIONS", text: I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" },
                    { id: "APP_INSTALLS", text:  I18N.getText('createAd', 'appInstalls'), val: "APP_INSTALLS" }
                ],
                billingEventsNotSupportCpa: [
                    { id: "IMPRESSIONS", text: I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" },
                    { id: "APP_INSTALLS", text: (I18N.getText('createAd', 'appInstalls') + I18N.getText('createAd', 'appInstallsNoPermission')), val: "APP_INSTALLS" ,disable:true}
                ]
            }, {
                id: "LINK_CLICKS",
                text:I18N.getText('createAd', 'linkClicks'),
                val: "LINK_CLICKS",
                billingEvents: [
                    { id: "LINK_CLICKS", text: I18N.getText('createAd', 'linkClicks'), val: "LINK_CLICKS" },
                    { id: "IMPRESSIONS", text: I18N.getText('createAd', 'impressions'), val: "IMPRESSIONS" }
                ]
            }]
        }

    };
    return me;
});
